1

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.

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • That's another issue solved by NLL – Boiethios Jul 17 '18 at 15:04
  • @Boiethios What do you mean? What is NLL? (it seems sarcastic, hope it's not, I try to do my best). – rap-2-h Jul 17 '18 at 15:06
  • 1
    There has been a bunch of questions like yours. NLL is a new feature soon coming to the compiler. For now, put your binding in a scope to "cancel" it at the end of the scope. – Boiethios Jul 17 '18 at 15:07
  • @Boiethios Ok thanks! Maybe you could post your comment as an answer? (even if it's similar to some other questions, maybe it could help users since I did not found a similar question (because I did not know how to search for that need)) – rap-2-h Jul 17 '18 at 15:09
  • @Boiethios Ok thank you. – rap-2-h Jul 17 '18 at 15:19
  • 2
    Questions closed as duplicates are not deleted; they stick around, for the explicit purpose of helping future users who cannot find the "canonical" question. It's better to have a network of duplicates that all link to a common target than a bunch of isolated questions with slightly different answers. – trent Jul 17 '18 at 15:33
  • @trentcl Thank you for your answer :) – rap-2-h Jul 17 '18 at 15:40

0 Answers0