Why can't I call a function which accept a param with type &'a mut A<'a> twice?

struct A<'a> {
    _a:PhantomData<&'a bool>
}

fn f<'a>(a: &'a mut A<'a>) {
    g(a);
    // cannot borrow `*a` as mutable more than once at a time [E0499] second mutable borrow occurs here
    g(a);
}

fn g<'a>(a: &'a mut A<'a>) {

}

if I remove 'a after &, everything becomes ok;
if I remove 'a from A's type parameters, everything becomes ok too.
So why did I got this borrow checking error?

It’s the equivalent of a deadlock in Rust’s static-rwlock model of borrowing. By using the same lifetime annotation ’a, you’re asserting that these two regions are identical:

  • The validity of the internal phantom-borrowed data, which must last at least until the struct A is dropped (otherwise, you might end up with a dangling phantom-reference)
  • The exclusive access guaranteed by the mutable reference

Thus, the exclusive access must extend until the referent is actually dropped. This naturally conflicts with any subsequent accesses.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.