Course contentsShow
← Rust
Lesson 226 of 1,9103. Borrowing and ReferencesFree lesson

Borrowing Struct Fields vs. Structs

Distinguish between borrowing an entire structure and borrowing a specific field.

In this lesson, you will learn how to choose between borrowing an entire structure and borrowing just one of its specific fields to satisfy the borrow checker.

When you work with a struct, you have two main ways to share its data. You can either pass a reference to the whole structure (&my_struct) or a reference to a single field within it (&my_struct.field). While both are valid, they affect how the rest of your code behaves.

Borrowing the Whole Struct

When you borrow an entire structure, the borrow checker treats the structure as a single unit. If you hold a reference to the whole struct, you are effectively "locking" the entire object. This means you cannot modify any part of that structure—even parts you aren’t currently using—until that reference goes out of scope.

Borrowing a Single Field

Rust is smart enough to perform "field-level borrowing." If you only need one piece of information from your struct, you can borrow just that field. This is powerful because it allows for more granular access. By borrowing &my_struct.field, you are only locking that specific field.

Consider this example:

struct Player {
    name: String,
    score: i32,
}

fn print_name(name: &String) {
    println!("Player: {}", name);
}

fn main() {
    let mut player = Player { name: String::from("Alice"), score: 10 };

    // We only borrow the 'name' field
    print_name(&player.name);

    // Because we only borrowed the field, the rest of the struct
    // remains flexible for other operations!
    player.score += 1; 
}

In the code above, print_name only cares about the name field. By passing &player.name instead of &player, we keep the player struct partially accessible. If we had borrowed the entire &player, the borrow checker might prevent us from modifying the score field, depending on the scope of that reference.

By borrowing only the specific field you need, you reduce the surface area of your borrows, which helps prevent unnecessary conflicts with the borrow checker and makes your functions more modular.

Key Takeaway: Borrowing an entire struct locks the whole object, while borrowing a single field limits the "lock" to that specific piece of data, allowing for greater flexibility in your code.