Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to understand nested borrow with the same lifetime?

I’m having a hard time understanding this snippet:

fn main() {}

fn f<'a>(mem: &'a mut &'a u8)  {
}

fn dp<'a>(mem: &'a mut &'a u8) {
    f(mem); // this line compiles fine
    f(mem); // This line when added, errors
}

The error message says this error is related with *mem is borrowed as mutable twice.

I know this &'a mut &'a u8 thing is incorrect, just wondering why the error message is like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

&mut T is invariant over T. Here, in your case T is &u8. The problem is that the inner and outer lifetimes are same. The inner lifetime 'a is "some" lifetime greater than the duration of the function dp(), but since it is behind a mutable reference it cannot be shortened to the duration of the function f() (remember &mut T is invariant over T). But the mutable reference (outer) is also 'a, as a result mem will stay borrowed after the first call to f(). Hence, the second call fails, since mem is already borrowed. You can fix this buy using different (i.e disjoint) inner & outer lifetimes.

You can read more about variance and lifetimes here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading