capypad
0 day streak
rust / intermediate
Snippet

Understanding Lifetimes in Rust

Lifetimes are Rust's way of ensuring memory safety without garbage collection. They track how long references are valid. The 'a lifetime annotation connects the input and output references, guaranteeing the returned reference won't outlive the inputs. Structs holding references must also declare lifetimes to ensure the data they reference lives long enough.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
 
struct ImportantExcerpt<'a> {
part: &'a str,
}
 
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Attention: {}", announcement);
self.part
}
}
Breakdown
1
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
Generic function with lifetime 'a. Both input references must live at least as long as 'a, and output lives at least 'a
2
struct ImportantExcerpt<'a>
Struct holds a reference, so it needs a lifetime parameter to tell Rust how long that reference is valid
3
fn announce_and_return(&self, announcement: &str) -> &str
Method returning a reference; lifetime is tied to &self, ensuring the returned reference is valid while the struct exists