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