Ownership of the fields of a struct when borrowing with mutable references

⚓ Rust    📅 2025-10-05    👤 surdeus    👁️ 6      

surdeus

I am following the Interactive Rust Book to learn about structs in Rust. I trying to understand how permissions work when only certain fields of a struct are borrowed. In this section, we see that when the x field of the struct p is mutably borrowed, the entire struct p loses it's R/W/O permissions.

image

Now, if we see the same example in the Quiz Question 2:
image

(coping the code for convenience)

struct Point {

  x: i32,

  y: i32,

}


fn main() {

  let mut p = Point { x: 1, y: 2 };

  let x = &mut p.x;  // Here both p and p.x lose their R/W/O permissions

  let y = &mut p.y;  // Then here, how can p.y be accessed if p itself has lost all permissions?

  *x += 1;

  *y += 1;

  println!("{} {}", p.x, p.y);

}

As stated in the answer, if Rust can understand that p.x refers to a different object than p.y or p why did even p lose the permissions in the first example? It seems inconsistent. What is the general rule for referencing fields and annotating permissions of a struct or elements of a container such as an array, vector, string etc when the entire container has lost permissions because one element was mutably borrowed?
Thanks!

8 posts - 5 participants

Read full topic

🏷️ Rust_feed