Why does this mutable borrow live beyond its scope?

In short, &'a mut Chain<'a> is extremely limiting and pervasive.

For an immutable reference &T<'a>, the compiler is allowed to shorten the lifetime of 'a when necessary to match other lifetimes or as part of NLL (this is not always the case, it depends on what T is). However, it cannot do so for mutable references &mut T<'a>, otherwise you could assign it a value with a shorter lifetime.

So when the compiler tries to reconcile the lifetimes when the reference and the parameter are linked &'a mut T<'a>, the lifetime of the reference is conceptually expanded to match the lifetime of the parameter. Which essentially means you’ve created a mutable borrow that will never be released.

Applying that knowledge to your question: creating a reference-based hierarchy is really only possible if the nested values are covariant over their lifetimes. Which excludes:

  • mutable references
  • trait objects
  • structs with interior mutability

Refer to these variations on the playground to see how these don’t quite work as expected.

See also:

Leave a Comment