&'a T
means "I know that a valid value of type T
exists at the address contained in this reference for at least as long as the region of code demarcated by 'a
".
The full answer depends on:
- what you think "live" and "lifetime" mean
- what you mean by "lifetime of the reference"
As stated in Why can't I store a value and a reference to that value in the same struct?, the "lifetime" of a value is not what most people expect:
As an analogy, think of it this way: During a person's life, they will reside in many different locations, each with a distinct address. A Rust lifetime is concerned with the address you currently reside at, not about whenever you will die in the future (although dying also changes your address). Every time you move it's relevant because your address is no longer valid.
A non-reference value has one or more lifetimes associated with it between when it is created and when it is destroyed, but on a single line of code it has only one that is relevant.
A reference has two lifetimes associated with it on a single line of code:
- How long the reference value itself is valid at the current memory address.
- How long the referred-to value is valid at its current memory address.
Here, the concrete lifetime of a
is [0, 2]. The concrete lifetime of b
is [1, 2]. Since b
refers to a
, that's also a related lifetime:
fn example() {
let a = 42; // 0 A
let b = &a; // 1 | B
println!("{}, {}", a, b); // 2 | |
}
As the reference depth increases, this continues — &&&&i32
has five associated lifetimes.
Most of the time, this doesn't matter because the compiler will automatically collapse lifetimes... when variance allows for it.
Additionally, since your example uses generic types, it's effectively expanded to:
pub struct Foo<'m, T: 'm> {
tx: &'m mut T,
}
That is, if the generic type T
contains any references, they must equal or outlive the lifetime 'm
.
See also: