rust / intermediate
Snippet
Basic Lifetime Annotations
Lifetimes ensure that references remain valid as long as they are needed. Annotating a struct with '<'a>' tells the compiler the struct cannot outlive the reference it holds.
snippet.rs
1
2
3
4
5
6
7
8
struct Excerpt<'a> {part: &'a str,}fn main() {let text = String::from("Rust is fast.");let first_word = Excerpt { part: &text[0..4] };}
Breakdown
1
struct Excerpt<'a> {
Defines 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.