Hello all,
I'm struggling in understanding the constraint between lifetime of a struct reference and one of its field. Concretely, why does the following code compile:
#[derive(Debug)]
#[repr(C)]
pub struct Foo<'a>(&'a u8);
struct WrapFoo<'a> {
inner: &'a Foo<'a>,
}
mod ffi {
extern "C" {
pub fn foo(s: &u8, f: *mut *const super::Foo);
}
}
pub fn foo<'a>(s: &'a u8) -> &'a Foo<'a> {
unsafe {
let mut f = std::mem::uninitialized();
ffi::foo(s, &mut f);
&*f
}
}
fn main() {
let x = 10u8;
let f; // lifetime 'a
{
let ff; // lifetime 'b
let wf;
{
ff = foo(&x);
wf = WrapFoo { inner: ff }; // should wf.f have lifetime &'b Foo<'b>?
}
f = wf.inner; // because 'a : 'b, how is it possible?
}
println!("{:?}", f);
}
The struct WrapFoo
contains a reference inner
to some Foo<'a>
, and this reference has also the lifetime 'a
.
There is a reference to f: 'a &Foo<_>
and another ff :'b &Foo<_>
where 'a: 'b
. Using
wf = WrapFoo { inner: ff }
I mean to restrict wf.inner:
&'b Foo<'b>`.
But surprisingly, I can leak 'b
to the larger lifetime 'a
with f = wf.inner
, how is it possible?
Many thanks for any help.