enum ManagedSlice<'a, T: 'a> {
Borrowed(&'a T),
Owned(T)
}
struct B<'a>{
m: ManagedSlice<'a, Vec<u8>>
}
impl<'a> B<'a> {
pub fn new() -> B<'a> {
let m = ManagedSlice::Owned(vec![]);
B{
m: m
}
}
}
fn main() {
let b = B::new();
}
I made this code to test if I really understand lifetimes. When I create let b = B::new()
I get a B<'x>
with a specific lifetime 'x
. In theory this should be the lifetime of m
. But as you see, m
's life is very short, living only inside new
.
What happens to a lifetime when something moves? Does m
get the lifetime of B
?
What about this modification:
enum ManagedSlice<'a, T: 'a> {
Borrowed(&'a T),
Owned(T)
}
struct B<'a>{
m: ManagedSlice<'a, Vec<u8>>
}
impl<'a> B<'a> {
pub fn new(s: &'a u8) -> B<'a> {
let m = ManagedSlice::Owned(vec![]);
B{
m: m
}
}
}
fn main() {
let b;
{
let n = 0;
b = B::new(&n);
}
}
now I'm forcing 'a
to have the lifetime of n
. I expected this to not compile since n
has a short life and b
gets the type B<lifetime of n>
, but b
has a lifetime greater than n
.
What is happening?