Search code examples
rustlifetime

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


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?


Solution

  • 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).