What does it mean for a type to have a static lifetime?
Asked Answered
B

1

7

I understand what it means for a borrow, trait, or struct to have a lifetime, but it doesn't make sense to me why a type would have one. My understanding of types is that they are an abstraction that is used at compile time, and they don't need to exist at all in the binary. For example, a struct with a two ints, a tuple of two ints, and a fixed-size array of two ints should all map to the same arrangement of values in memory when compiled, and the code would use byte offsets to find those two values. If I am correct about that, the concept of a lifetime shouldn't apply to types at all, so the following two structs would be equivalent:

pub struct Foo<T> {
    foo: T
}

pub struct Bar<T: 'static> {
    bar: T
}

Beyond just being equivalent, the syntax wouldn't exist at all. I must be misunderstanding something, and extensive googling has not helped. What is the purpose of type lifetimes, and when are they supposed to be used?

Batiste answered 3/4, 2021 at 22:6 Comment(2)
See last paragraph here for lifetime bounds on T. Also see RFC 0192.Annmarie
I read that page, and it makes sense up to just before that point. The thing that seems weird is that any application I can think of for that kind of constraint could be handled by a constraint on a value instead. For example, when a closure borrows something so it can return references to it, the closure's lifetime is limited to the lifetime of that borrow, but the type of the closure should still last forever.Batiste
O
6

T can carry lifetimes shorter than 'static. For instance, T could be some &'a str (for some 'a), so Foo<T> becomes Foo<&'a str> and therefore has a bound to 'a, which may be shorter than 'static.

The first definition accepts any T and will be bound in its lifetime to T. The second definition says that T must not contain lifetimes shorter than 'static (T could be &'static str, String or anything else that is bound by 'static).

Overbalance answered 3/4, 2021 at 23:15 Comment(2)
Okay, I think that makes sense. If I'm understanding correctly, the lifetime of the type doesn't mean the type becomes invalid when the lifetime ends, it means the value filling in that type has an associated lifetime that might expire. So this would be used when a struct takes ownership of something that contains borrowed data, to enforce that the instance of the struct doesn't outlive its owned value that has a borrowed value within. Did I get that right?Batiste
The compiler will figure out what lifetime restrictions come with Foo<T> for any T, including if T contains lifetimes shorter than 'static. If you construct a Foo<&'a str> for some 'a and then try to reassign the value for T with some other &'b str where 'b is shorter than 'a, the compiler will error out.Overbalance

© 2022 - 2024 — McMap. All rights reserved.