While attempting to implement an Iterator
from a struct that holds a mutable reference I came across this oddity: When implementing a method that returns a reference on a struct that holds a reference, the lifetime parameter on self
can be omitted, as in this example
struct Holder<'a> {
data: &'a [u8],
}
impl<'a> Holder<'a> {
fn first(&mut self) -> &'a [u8] {
&self.data[0..1]
}
}
fn main() {
let mut data = vec!(1, 2, 3);
let h = &mut Holder{data: &mut data[..]};
println!("{:?}", h.first());
}
However, if I modify the code ever so slightly, making the data member a mutable reference, the compiler helpfully tells me that lifetime might not live long enough
without also adding a lifetime parameter 'a
to the &mut self
parameter on line 6.
Why does it matter whether data
is a shared or mutable reference? The reason I would like to avoid the need to add the lifetime parameter to self is that it would prevent me from having that method be an implementation of some trait defined without the lifetime parameter.
I realise that it is possible to use the interior mutability pattern to hold a shared reference in Holder
, but that seems like a less desirable solution