rust / intermediate
Snippet
Lifetimes in Struct Definitions: Ensuring Reference Validity
Lifetimes are Rust's way of ensuring memory safety without garbage collection. When a struct holds a reference, you must annotate how long that reference is valid. The lifetime parameter 'a in ImportantExcerpt<'a> tells the compiler: 'the reference stored in part will be valid for at least as long as the struct instance exists.' This prevents dangling references at compile time.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct ImportantExcerpt<'a> {part: &'a str,}impl<'a> ImportantExcerpt<'a> {fn new(text: &'a str) -> Self {ImportantExcerpt { part: text }}fn announce_and_return(&self, announcement: &str) -> &str {println!("Announcement: {}", announcement);self.part}}fn main() {let text = String::from("The only thing we have to fear is fear itself.");let excerpt = ImportantExcerpt::new(&text);println!("Excerpt: {}", excerpt.part);}
Breakdown
1
struct ImportantExcerpt<'a> {
Declares a struct with a lifetime parameter 'a
2
part: &'a str,
The field part is a reference that must live at least as long as 'a
3
impl<'a> ImportantExcerpt<'a> {
Implementation block also carries the lifetime parameter to connect it to the struct
4
fn announce_and_return(&self, announcement: &str) -> &str {
Return type must use same lifetime 'a to guarantee safety
5
self.part
Returns a reference guaranteed to be valid for lifetime 'a