Sargis
Sargis

Reputation: 111

Rust multiple mutable borrowing

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!

Upvotes: 9

Views: 2976

Answers (2)

Guillaume Quintard
Guillaume Quintard

Reputation: 619

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.

Upvotes: 5

mcarton
mcarton

Reputation: 30101

You are probably benefiting from non-lexical lifetimes which have been enabled by default since Rust 1.30 while using the 2018 edition.

See also What are non-lexical lifetimes?.

Upvotes: 12

Related Questions