C.W.K.
Stream
Lesson 02 of 05 · published

Lifetime Annotation Syntax

~11 min · lifetimes, annotations, syntax

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

Lifetime annotations look alien the first time: &'a str, fn foo<'a>(...). Let's decode the syntax so it stops being scary.

Reading 'a

An apostrophe followed by a name is a lifetime parameter: 'a reads 'lifetime a.' It's a generic parameter, just like T is for types — it stands for 'some region of code,' and the compiler fills in the concrete region at each call. &'a str means 'a reference to a str, valid for the region 'a.'

Declaring before using

Just like type generics, you declare a lifetime in angle brackets before you use it: fn foo<'a>(x: &'a str). The angle-bracket part introduces the name; the &'a str uses it. This is exactly parallel to fn foo<T>(x: T) — lifetimes are generics over regions instead of over types.

The name is arbitrary; the relationships are everything. 'a, 'b, 'life — the letters mean nothing on their own. What matters is which references share the same lifetime name, because that's what ties their validity together.

What an annotation promises

When you write two parameters with the same 'a, you're telling the compiler: 'treat these as sharing one region — the output is valid only as long as both inputs are.' You're not extending or shortening any life; you're stating a constraint the compiler will then enforce at every call site.

Code

Decoding the syntax·rust
// <'a> declares the lifetime; &'a str uses it.
// This says: the returned reference lives as long as BOTH inputs.
fn pick<'a>(first: &'a str, second: &'a str, use_first: bool) -> &'a str {
    if use_first { first } else { second }
}

fn main() {
    let a = String::from("alpha");
    let b = String::from("beta");
    let chosen = pick(&a, &b, true);
    println!("{chosen}");
}

External links

Exercise

Take the pick function above and change one parameter to a different lifetime (declare both 'a and 'b, give second the 'b). Try to still return second and read the compiler error. What relationship is the compiler missing?
Hint
If the output is declared &'a str but you return the 'b parameter, the compiler can't prove the 'b data outlives 'a. The annotation now says something that isn't guaranteed — that's the error.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.