Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 921
Sargis Avatar asked Oct 20 '18 20:10

Sargis


2 Answers

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?.

like image 61
mcarton Avatar answered Nov 03 '22 20:11

mcarton


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.

like image 36
Guillaume Quintard Avatar answered Nov 03 '22 21:11

Guillaume Quintard