rust / intermediate
Snippet
Lifetimes in Struct Definitions
When a struct holds references, Rust needs to know how long those references will be valid. Lifetime annotations ('a) establish a contract that the references inside the struct will not outlive the data they reference. The struct cannot exist longer than the data it references.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Quote<'a> {content: &'a str,author: &'a str,}fn main() {let text = String::from("The only way to do great work is to love what you do.");let quote = Quote {content: &text,author: &text,};println!("{} - {}", quote.content, quote.author);}
Breakdown
1
struct Quote<'a> {
Declares a lifetime parameter 'a that any reference in this struct must satisfy
2
content: &'a str,
A borrowed string slice that must live at least as long as lifetime 'a
3
author: &'a str,
Both references share the same lifetime, ensuring consistent borrowing duration
4
let quote = Quote { content: &text, author: &text };
Both references point to the same owned String, satisfying the lifetime constraint