This codes:
struct A {
x: i32
}
struct B {
y: A
}
impl B {
pub fn new(y: A) -> Self {
B {y: y}
}
pub fn fn1(&mut self) -> &mut Self {
let z = &self.y;
println!("{:?}", z.x);
self
}
}
fn main() {
let a = A {x: 10};
B::new(a).fn1();
}
Produces this error:
Compiling playground v0.0.1 (file:///playground)
error[E0502]: cannot borrow `*self` as mutable because `self.y` is also borrowed as immutable
--> src/main.rs:17:9
|
15 | let z = &self.y;
| ------ immutable borrow occurs here
16 | println!("{:?}", z.x);
17 | self
| ^^^^ mutable borrow occurs here
18 | }
| - immutable borrow ends here
It's a simplified example, the code is more complex. I would like to create a var that is a reference to a property of a struct. The relevant part is:
pub fn fn1(&mut self) -> &mut Self {
let z = &self.y;
println!("{:?}", z.x);
self
}
It works if I do not use a local var z
and directly use self.y.x
:
pub fn fn1(&mut self) -> &mut Self {
println!("{:?}", self.y.x);
self
}
Assuming my code is a bit more complex and I would like to use a temporary variable which is a reference one property of the struct (a.k.a B
), is there a way to set z
to self.y
without copying the content of y
? (so I thought I need a reference because I don't ant to copy).
Maybe my question is not clear enough, feel free to ask, I can edit if required! Sorry if it's a duplicate. And sorry for the title too.