rust / intermediate
Snippet
Lifetimes in Struct Definitions
Lifetimes ensure references in structs don't outlive the data they reference. The struct holds a reference with lifetime 'a, which must be at least as long as the struct instance itself. This prevents dangling references at compile time.
snippet.rs
1
2
3
4
5
6
7
8
9
struct Excerpt<'a> {part: &'a str,}fn main() {let text = String::from("Hello world");let excerpt = Excerpt { part: &text[6..11] };println!("Excerpt: {}", excerpt.part);}
Breakdown
1
struct Excerpt<'a> {
Struct definition with lifetime parameter 'a
2
part: &'a str,
Reference to str that must live at least as long as 'a
3
let excerpt = Excerpt { part: &text[6..11] };
Creates instance - excerpt borrows from text, lifetimes are connected