Sub topic 3
Reading and changing fields
This chapter assumes you can define a struct and create an instance. It also assumes you know the basics of moves, &, and &mut. Here you will learn how field access works, how mutability applies to fields, and which borrow checker errors you are most likely to hit.
Reading a field with dot syntax
You read a field with instance.field_name. You can chain dots to reach into nested values, and tuple fields use numeric positions.
#[derive(Debug)]
struct Player {
name: String,
score: u32,
position: (i32, i32),
}
fn main() {
let p = Player {
name: String::from("Ada"),
score: 10,
position: (4, -2),
};
println!("{} has {} points", p.name, p.score);
println!("x = {}, y = {}", p.position.0, p.position.1);
}Reading a field is an expression that produces a value, so ownership rules apply to it. The next sections cover what that means.
Mutability belongs to the binding
Rust has no per-field mut keyword. Mutability is a property of the whole instance, set by the variable that holds it. If the binding is mut, every field can change. If it is not, none can.
#[derive(Debug)]
struct Player {
name: String,
score: u32,
position: (i32, i32),
}
fn main() {
let mut p = Player {
name: String::from("Ada"),
score: 10,
position: (0, 0),
};
p.score += 5;
p.position.0 += 3;
p.name.push_str(" Lovelace");
println!("{:?}", p);
}The output is Player { name: "Ada Lovelace", score: 15, position: (3, 0) }.
If you remove mut from the binding, the compiler rejects every assignment with error E0594, "cannot assign to p.score, as p is not declared as mutable". The fix is to change the binding, not the field.
Fields through references
Dot syntax works the same way through & and &mut. Rust automatically dereferences the reference when you access a field, so you never write (*p).score.
struct Player {
name: String,
score: u32,
}
fn show(p: &Player) {
println!("{}: {}", p.name, p.score);
}
fn bump(p: &mut Player) {
p.score += 1;
}
fn main() {
let mut p = Player {
name: String::from("Ada"),
score: 10,
};
bump(&mut p);
show(&p);
}Through a &Player you can read fields but not assign to them. Through a &mut Player you can do both. Mutability follows the kind of reference, not the original binding. You can only create &mut p if p was declared mut.
What reading a field does to ownership
let x = p.field; is a move or a copy, depending on the field's type. This surprises many intermediate learners.
- A
Copytype such asu32orboolis copied. The struct is unchanged. - A non-
Copytype such asStringorVec<T>is moved out of the struct. - Behind a reference, you cannot move out of a field at all.
Partial moves
When you own the struct, moving one field out leaves the other fields usable. This is a partial move.
struct User {
name: String,
email: String,
age: u32,
}
fn main() {
let u = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
age: 36,
};
let name = u.name; // moves only the name field
println!("{}", name);
println!("{}", u.email); // still valid
println!("{}", u.age); // still valid
// println!("{}", u.name); // error E0382: borrow of moved value
// let whole = u; // error E0382: use of partially moved value
}After a partial move, you cannot use the struct as a whole, which includes passing it to a function or calling a method on it. Individual fields that were not moved stay usable. A partial move is only allowed if the struct type does not implement Drop. Otherwise the compiler reports E0509.
Taking a field out of a borrowed struct
Suppose you hold &mut Player and want to take the String out of a field. Direct assignment to a local fails with E0507. Use std::mem::take or std::mem::replace, which swap a new value in so the struct is never left empty.
use std::mem;
struct Player {
name: String,
score: u32,
}
fn rename(p: &mut Player, new_name: &str) -> String {
mem::replace(&mut p.name, new_name.to_string())
}
fn drain_name(p: &mut Player) -> String {
mem::take(&mut p.name) // leaves an empty String; requires Default
}
fn main() {
let mut p = Player {
name: String::from("Ada"),
score: 1,
};
let old = rename(&mut p, "Grace");
println!("old = {old}, new = {}, score = {}", p.name, p.score);
let taken = drain_name(&mut p);
println!("taken = {taken}, left = '{}'", p.name);
}If you only need to look at the value, borrow it with &p.name or call p.name.clone() instead.
Borrowing individual fields
The borrow checker tracks each field separately when you access fields directly. You can hold a mutable borrow of one field and use another field at the same time.
struct Stats {
hits: u32,
log: Vec<String>,
}
fn main() {
let mut s = Stats {
hits: 0,
log: Vec::new(),
};
let log = &mut s.log; // borrows only s.log
s.hits += 1; // fine: a different field
log.push(String::from("hit"));
println!("{} {:?}", s.hits, s.log);
}This analysis stops at method boundaries. A method like fn log_mut(&mut self) -> &mut Vec<String> borrows all of self, because the compiler checks callers using only the method's signature. If s.log_mut() replaced &mut s.log above, the line s.hits += 1 would fail with E0499 or E0502 while the returned reference is alive.
| Access style | What is borrowed | Can another field be used meanwhile? |
|---|---|---|
| `&mut s.log` | Only the `log` field | Yes |
| `s.log_mut()` | All of `s` | No, until the returned reference is dropped |
| `&s.log` | Only the `log` field, shared | Yes, including reads and writes of other fields |
When a method needs two fields at once, borrow them directly inside the method body rather than calling other &mut self methods.
Common errors
- E0594, cannot assign to a field. The binding or reference is not mutable. Add
mutto the binding, or take&mutinstead of&. - E0382, use of moved or partially moved value. You moved a non-
Copyfield out and then used the whole struct or that field again. Borrow with&, clone, or restructure. - E0507, cannot move out of a borrowed field. You tried
let s = r.name;through a reference. Use&r.name,.clone(), ormem::take. - E0502 or E0499 around method calls. A method taking
&selfor&mut selfborrows the whole struct. Access the fields directly when you need them separately.
Exercise
Given struct Pair { a: String, b: String } and let p = Pair { a: "x".into(), b: "y".into() };, which of these lines compile when placed after let a = p.a;? (1) println!("{}", p.b); (2) println!("{}", p.a); (3) let q = p;
Show answer
Only line 1 compiles. p.a was moved out, so line 2 uses a moved value. Line 3 tries to move p as a whole after a partial move, which is also an error. p.b was not moved, so it is still usable.
Exercise
A function has the signature fn take_name(p: &mut Player) -> String and the body p.name. The compiler reports E0507. Rewrite the body so it returns the name and leaves an empty string in the struct.
Show answer
Use std::mem::take(&mut p.name). It moves the current value out and puts String::default(), an empty string, in its place, so the struct stays valid.