I stumbled upon a case where I need the lifetime to be as narrow as possible so that if I have any generic types references under this lifetime (&'a T
), I don't need them to be bound to the lifetime (where T: 'a
). The need comes from a vector of references that I want to re-use under different lifetimes. A simple example:
struct Foo<'a> {
bar: Vec<&'a bool>,
}
impl<'a> Foo<'a> {
fn reset(mut self) -> Foo<'static> { // need 'zero here!
use std::mem::transmute;
self.bar.clear();
// technically safe, since the vector is empty
Foo {
bar: unsafe { transmute(self.bar) },
}
}
}
// using 'zero here will probably require another transmute(), but it's still safe
impl Foo<'static> {
fn fill<'a>(self, element: &'a bool) -> Foo<'a> {
let mut bar = self.bar;
bar.push(element);
Foo {
bar: bar,
}
}
}
The example uses 'static
as a "rest" point, where the vector is guaranteed to be empty. The real case though is more ugly. Also, I can't afford 'static
bound on my generic parameters, and it shouldn't be needed in the first place, since I only use 'static
references in an empty vector. Hence, I need a 'zero
lifetime for the "rest" point of my reference vector, so that no additional (unneeded) bounds are placed on the used types.
From Rust point of view, anything can't exist with 'zero
lifetime. But in my case it's not really used for any living reference, it's just used in the type signature, so I don't see any contradiction with the borrow checker rules.