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.
Lifetimes in structs in 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.
'a ensures the string slice lives as long as the Book.struct Book<'a> {
title: &'a str,
}T with lifetime 'a.struct Container<'a, T> {
item: &'a T,
}'a, meaning they must both live at least as long as 'a.struct Pair<'a> { first: &'a str, second: &'a str, }
This program creates a Book struct holding a reference to a string. The lifetime 'a ensures the reference is valid while book exists.
struct Book<'a> { title: &'a str, } fn main() { let name = String::from("Rust Book"); let book = Book { title: &name }; println!("Book title: {}", book.title); }
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.
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.