CodeBlanks Logo Icon CodeBlanks

What is a lifetime?

Learn what lifetimes do for references.

What is a lifetime?

Every reference has a lifetime: the region of code where it's valid. The compiler checks that a reference doesn't outlive the value it points to by comparing lifetimes. Most of the time lifetimes are inferred and never written:

let r;                 // ---------+-- lifetime of r
{                      //          |
    let x = 5;         // -+-- x   |
    r = &x;            //  |       |
}                      // -+ x ends
// println!("{r}");    // error E0597: x doesn't live long enough

Lifetimes do nothing at runtime; they are purely a compile-time check.

The 'static lifetime

'static is the longest lifetime. String literals and static variables have it, so they can be returned safely from a function:

fn karsilama() -> &'static str {
    "merhaba"
}

static SURUM: &str = "1.0";

Even if a compiler error suggests 'static, the right fix is often to return an owned value (String) instead of a reference.

Practice Static text

Write fn karsilama() -> &'static str returning "merhaba". Print the result and its length separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn karsilama() -> &'static str {
    "merhaba"
}

fn main() {
    let s = karsilama();
    println!("{} {}", s, s.len());
}

Expected output

merhaba 7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>&amp;'static str</code> mean?

  • Text on the stack
  • A global variable
  • A text reference valid until the end of the program Correct answer
  • An unchangeable String

Explanation: String literals are embedded in the program binary and are always valid, so their type is &'static str.

2 Static lifetime

Question
fn karsilama() -> &____ str {
    "merhaba"
}
Answer
fn karsilama() -> &'static str {
    "merhaba"
}

Explanation: String literals live until the end of the program: &'static str.

3 Value and lifetime

Term Meaning
"merhaba" 'static
fn f() -> &'static str Can return a literal
let x = 5; &x Scope of x
String::from("a") Owned, no lifetime

All lessons in Intermediate