0
0
Rustprogramming~7 mins

Lifetimes in functions in Rust

Choose your learning style9 modes available
Introduction

Lifetimes help Rust know how long references are valid. This keeps your program safe from using data that no longer exists.

When you write a function that returns a reference to data passed in.
When you want to make sure references inside a function don't outlive the data they point to.
When you have multiple references as inputs and want to relate their lifetimes.
When you want to avoid copying data but still keep safety with references.
Syntax
Rust
fn function_name<'a>(param: &'a Type) -> &'a Type {
    // function body
}

The &'a means a reference with lifetime 'a.

You declare lifetime parameters with <'a> after the function name.

Examples
This function returns a part of the input string slice. The lifetime 'a ties the output to the input, so Rust knows the returned reference is valid as long as the input is.
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 function returns the longer of two string slices. Both inputs and the output share the same lifetime 'a, so Rust knows the output reference is valid as long as both inputs are.
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
Sample Program

This program defines a function longest that returns the longer of two string slices. The lifetime 'a ensures the returned reference is valid as long as both inputs are valid. In main, it prints the longer string.

Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let string1 = String::from("apple");
    let string2 = "banana";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is: {}", result);
}
OutputSuccess
Important Notes

Every reference in Rust has a lifetime, even if you don't write it explicitly.

Using lifetimes helps prevent bugs where you use data after it's gone.

If you don't specify lifetimes when needed, Rust will give an error to keep your code safe.

Summary

Lifetimes tell Rust how long references are valid.

Functions with references often need lifetime annotations to connect input and output lifetimes.

This helps Rust prevent bugs with invalid references and keeps your program safe.