0
0
Rustprogramming~5 mins

Lifetimes in structs in Rust

Choose your learning style9 modes available
Introduction

We use lifetimes in structs to tell Rust how long references inside the struct should live. This helps Rust keep your program safe from errors like using data that no longer exists.

When you want a struct to hold a reference to data owned elsewhere.
When you need to ensure the data a struct points to lives long enough.
When you want to avoid copying data by using references inside structs.
When you want Rust to check that your struct does not outlive the data it refers to.
Syntax
Rust
struct StructName<'a> {
    field: &'a Type,
}

The 'a is a lifetime parameter that tells Rust how long the reference inside the struct lives.

Every reference inside the struct that needs a lifetime must use the same lifetime parameter or its own.

Examples
This struct holds a reference to a string slice. The lifetime 'a ensures the string slice lives as long as the Book.
Rust
struct Book<'a> {
    title: &'a str,
}
This struct holds a reference to any type T with lifetime 'a.
Rust
struct Container<'a, T> {
    item: &'a T,
}
Both references share the same lifetime 'a, meaning they must both live at least as long as 'a.
Rust
struct Pair<'a> {
    first: &'a str,
    second: &'a str,
}
Sample Program

This program creates a Book struct holding a reference to a string. The lifetime 'a ensures the reference is valid while book exists.

Rust
struct Book<'a> {
    title: &'a str,
}

fn main() {
    let name = String::from("Rust Book");
    let book = Book { title: &name };
    println!("Book title: {}", book.title);
}
OutputSuccess
Important Notes

Lifetime annotations do not change how long data lives; they only tell Rust how references relate to each other.

If you forget to add lifetimes to structs with references, Rust will give an error asking for them.

You can have multiple lifetime parameters if your struct holds references with different lifetimes.

Summary

Lifetimes in structs tell Rust how long references inside the struct are valid.

Use lifetime parameters like 'a to connect the struct's references to external data.

This helps Rust prevent bugs from using invalid references.