If you want to give an exclusive reference that guarantees validity for the entire duration of 'a, then this works:
struct MutWrap<'a>(&'a mut u8);
impl<'a> MutWrap<'a> {
fn inner(&'a mut self) -> &'a mut u8 {
self.0
}
}
although it's pretty useless, because you can call such method only once anyway (since it promises exclusive access for the entire lifetime, there's only one whole lifetime and one exclusive access to give). Usually fn borrow<'short>(&'short mut self) -> &'short mut u8
is used (which is the default, and the 'short
label can be omitted).
Because the syntax you want is giving a promise that it cannot keep.
You can't have shared &self
that can be called many times, and each time guarantee that it's an exclusive reference that guarantees that nothing else can have it at the same time, while also allowing everything else get it anytime it wants.
Your syntax also means &'short self
-> &'long u8
, which means that you "lock" self
only for a short time (which would allow it to be called again after the short time), but also promise that what it has lent remains locked exclusively and valid for a long time (so allowing more "exclusive" duplicate references to be given out again before the long time ends).
That code is just a paradox.
Note that lifetimes of loans are analyzed at compile time, so they must follow rules of lifetime annotations and general rules of the borrow checker, and the compiler can't be too smart about how they are used in practice.
If you need to flexibly give out many references, and mutate the data at the same time, you need interior mutability. You can have:
fn inner(&self) -> &'a RefCell<T> // or Rc<RefCell<T>>
And this allows the program to track actual usage of the references and exclusivity at run time.