0
0
Rustprogramming~5 mins

Variable lifetime basics in Rust

Choose your learning style9 modes available
Introduction

Variable lifetime tells us how long a variable stays usable in a program. It helps keep programs safe and free from errors.

When you want to make sure a reference does not outlive the data it points to.
When you pass references between functions and want to avoid mistakes.
When you want to understand why Rust sometimes asks for lifetime annotations.
When you want to prevent bugs related to using data that no longer exists.
Syntax
Rust
fn example<'a>(input: &'a str) -> &'a str {
    input
}

Lifetime annotations use apostrophe and a name like 'a.

They tell Rust how long references are valid.

Examples
This function returns the first word from a string slice. The lifetime 'a ensures the returned slice lives as long as the input.
Rust
fn first_word<'a>(s: &'a str) -> &'a str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[..]
}
This code compiles due to lifetime elision. Rust infers the lifetime 'a from the input reference parameter.
Rust
fn no_lifetime(x: &str) -> &str {
    x
}
Sample Program

This program finds and prints the first word of a string. The lifetime 'a ensures the returned slice is valid as long as the input string.

Rust
fn main() {
    let string = String::from("hello world");
    let word = first_word(&string);
    println!("First word: {}", word);
}

fn first_word<'a>(s: &'a str) -> &'a str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[..]
}
OutputSuccess
Important Notes

Rust uses lifetimes to prevent dangling references and memory bugs.

Most of the time, Rust can figure out lifetimes automatically (called lifetime elision).

When Rust cannot guess, you add lifetime annotations like &'a.

Summary

Variable lifetime tells how long a reference is valid.

Use lifetime annotations to help Rust understand reference scopes.

This keeps programs safe from using invalid data.