Lifetime annotation - things that are not clear:
⚓ Rust 📅 2026-04-27 👤 surdeus 👁️ 1Question1: I see life times noted as 'a, or 'b and sometimes '_
I presume the 'a or 'b are arbitrary names and It seems to be that I can use any letter in the alphabet. and in fact I can use a ascii text word if I want to, except that the word 'static is a special reserved lifetime.
And what is the significance of the '_, I have seen '_' used as a dont care variable name.
Does that mean, we are saying the life time is also don't care?
Question2: Where should lifetimes be annotated?
ie: For example in this: structure declaration
pub struct FooBuffer<'a> {
buffer: &'a mut [u8],.
cursor : usize
}
First the structure holds a reference to a buffer.
The <'a> attached to the structure name and the buffer reference means that as long as the Structure is valid, the buffer is also valid?
Is that understanding correct?
Question 3 - Sometimes the compiler talks about lifetime 1, and lifetime 2 - but no where in my code do I have a numeric lifetime it is always a letter like: a, b or c
Question 4: Why do I sometimes need to give the impl a lifetime and the struct a lifetime again?
Example, sometimes I need to do this:
impl<'b> FooBuffer<'b> {
pub fn new( buf: &'b mut [u8] ) -> Self {
Self {
cursor : 0,
buffer : buf,
}
}
}
What is the purpose of the 'b on the implementation, what is that telling me? And why do I need another annotation on the Buffer?
Syntactically - it seems that sometimes the lifetime names must match, but other times they do not. Where are the rules that describe the names.? And when they must match other things and when they do not need to match other things.
And why does the lifetimes used for a function argument , in this case the pub fn new() need to match the lifetime of the impl and the Structure name at the start? Where is this described in the documentation?
3 posts - 3 participants
🏷️ Rust_feed