Rust multiple mutable borrowing

Viewed 2250

I'm trying Rust and have issues with understanding "borrowing".

struct Foo<T> {
    data: T,
}

impl<T> Foo<T> {
    fn new(data: T) -> Self {
        Foo {
            data: data,
        }
    }
}

fn main() {
    let mut foo = Foo::new("hello");

    let x = &mut foo;
    let y = &mut foo;

    println!("{}", foo.data);

}

Why this code compile without error? After all, I'm get a multiple mutable references on foo. The following is written to documentation:

The Rules of References
Let’s recap what we’ve discussed about references:

a) At any given time, you can have either (but not both of) one mutable reference or any number of immutable references.

b) References must always be valid.

What is the reason for this behavior? Thanks!

2 Answers

On my rust version (1.29.1), I do have the multi-borrow errors.

I think you are benefiting from non-lexical lifetimes here, that or the compiler smartly optimizes* the code as:

let mut foo = Foo::new("hello");

{ let x = &mut foo; }
{ let y = &mut foo; }

println!("{}", foo.data);

which works because you are not using x and y.

*: from @mcarton: optimizations occurs after the borrow-check pass, so the only option is NLL.

Related