The example code below is somewhat crafted but illustrates my major concern. The code compiles perfectly.
struct SliceWrapper<'a>(&'a mut[i32]);
impl<'a> SliceWrapper<'a> {
fn clear(&mut self) {
self.0 = &mut [];
}
}
fn main() {
let slice = &mut [1, 2, 3];
let mut wrapper = SliceWrapper(slice);
wrapper.clear();
}
The line self.0 = &mut [];
works but is very strange if we look at their lifetimes: a reference to a local variable is assigned to self.0
, which lives beyond the method call clear()
.
What makes it more confusing is that if I change that line to self.0 = &mut [0];
, then the compiler will throw me an error saying: creates a temporary which is freed while still in use.
So I guess the Rust compiler treats the lifetime of &mut []
differently. Is that true? What is the precise lifetime rule for &mut []
?