use std::marker::PhantomData;
struct S<'a, A> {
_phantom: PhantomData<*const A>,
value: &'a i32,
}
fn foo<'a, A>(value: &'a i32) {
let s: &'a S<'a, A> = &S {
_phantom: PhantomData,
value,
};
}
fn main() {}
Struct S
actually don't owns generic argument A
, so lifetime of A
don't relate to lifetime of S
. However Rust compiler output error in let s: &'a S<'a, A>
:
the parameter type `A` may not live long enough
...so that the reference type `&'a S<'a, A>` does not outlive the data it points at
consider adding an explicit lifetime bound...: `A: 'a`
Why is lifetime of A
bounded? Can we get independent A
from the lifetime of S
?
(Edit) The above code has another problem about reference to S
in foo
. More healthy code is:
use std::marker::PhantomData;
struct S<'a, A> where Self: 'a {
_phantom: PhantomData<*const A>,
value: &'a i32,
}
fn foo<'a, A>(value: &'a i32) {
let s: S<'a, A> = S {
_phantom: PhantomData,
value,
};
}
fn main() {}