Borrowing references to attributes in a struct

It’s a feature of the language. From the compiler point of view, there is no way for it to know that it’s safe to call your set() function while a is borrowed via get().

Your get() function borrows b mutably, and returns a reference, thus b will remain borrowed until this reference goes out of scope.

You have several way of handling this:

  1. Separate your two fields into two different structs

  2. Move the code which needs to access both attribute inside a method of B

  3. Make your attributes public, you will thus be able to directly get references to them

  4. Compute the new value before setting it, like this:

    fn main() {
        let a = Box::new(A { i: 47 });
        let mut b = B { a: a, j: 1 };
        let newval = {
            let a_ref = b.get();
            foo(a_ref)
        };
        b.set(newval);
    }
    

Leave a Comment