Skip to content

Lifetime checker only checks the signature of a type and not its content #35852

Closed
@tomaka

Description

@tomaka
trait Foo {
    type AssociatedType;

    fn build_associated_type(&self) -> Self::AssociatedType;

    fn through_carrier(self) -> Carrier<Self> where Self: Sized {
        let at = self.build_associated_type();
        Carrier { inner: at }
    }
}


struct FooImpl<'a> { inside: &'a u32 }

impl<'a> Foo for FooImpl<'a> {
    type AssociatedType = u32;
    fn build_associated_type(&self) -> u32 { *self.inside }
}


struct Carrier<T: Foo> { inner: T::AssociatedType }



fn must_be_static<T: 'static>(_: T) {}


fn main() {
    let data = 3;
    let foo_impl = FooImpl { inside: &data };
    let carrier = foo_impl.through_carrier();
    must_be_static(carrier);
}

This fails to compile at the call to must_be_static because: data does not live long enough, reference must be valid for the static lifetime.

When we call must_be_static(carrier), the type of carrier is Carrier<FooImpl<'a>>. Rustc presumably sees that there's a 'a and fails the compilation, since the parameter of must_be_static must be static.

However the inside of Carrier<FooImpl<'a>> is actually just a u32, which is static. Even though the type signature contains a lifetime, the actual content of the struct does not. Therefore this code should in theory compile.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions