Is T<'a>: 'b syntactic sugar for 'a: 'b?

134 Views Asked by At

Trying to understand the meaning of binding a type by a lifetime in a where clause.

My current understanding is that it desugars to lifetime bounds for every lifetime the type is parametrized in.

For instance &'a T: 'b would desugar to 'a: 'b as & are parametrized in 1 lifetime, and i32: 'a desugars to nothing, since there are no lifetime parameters (so it always holds true).

Could someone with more insight into rustc implementation confirm this? If there are nuances/differences and these are not equivalent, please correct my understanding.

Example:


fn test<'a, T: ?Sized>(p: &'a T)
where
    &'a i32: 'static,
{
}

fn test2<'a, T: ?Sized>(p: &'a T)
where
    'a: 'static,
{
}

fn main() {
    let string = String::from("hello");
    test(&string);
    test2(&string);
}

Both calls fail with the same error. The i32 type used in the bound in test has nothing to do with concrete types I'm passing.

1

There are 1 best solutions below

8
cafce25 On

No, T<'a>: 'b is not syntax sugar or equivalent to 'a: b', it implies all references (also the unmentioned, invisible ones) in T have to live as long as well. So &'a X: 'b implies that 'a has to outlive 'b ('a: 'b), but additionally all references in X also have to outlive 'b.

If a value is to be valid for a lifetime, all references in it also have to live at least as long or else you have an invalid value.