Rust
Struct lifetimes
Use lifetime parameters in structs that hold references.
Struct lifetimes
If a struct holds a reference, the field's lifetime must be stated in the struct definition. This means "the struct can't outlive the data it points to":
struct Alinti<'a> {
parca: &'a str,
}
let roman = String::from("Bir varmış. Bir yokmuş.");
let ilk = roman.split('.').next().unwrap();
let a = Alinti { parca: ilk };
a must finish being used before roman is dropped. This approach is used to split large texts into pieces without copying.
Methods on a struct with a lifetime
The lifetime parameter is also declared on the impl block. If a method returns the reference the struct holds, returning it with 'a lets the result live as long as the source, independent of the struct:
impl<'a> Alinti<'a> {
fn uzunluk(&self) -> usize {
self.parca.chars().count()
}
fn parca(&self) -> &'a str {
self.parca
}
}
Exercise Quote
Write the Alinti<'a> struct above and the uzunluk and parca methods. Quote the first sentence (split('.')) of the text "Bir varmış. Bir yokmuş."; print the piece and its character count separated by a space.
Show example solution
struct Alinti<'a> {
parca: &'a str,
}
impl<'a> Alinti<'a> {
fn uzunluk(&self) -> usize {
self.parca.chars().count()
}
fn parca(&self) -> &'a str {
self.parca
}
}
fn main() {
let roman = String::from("Bir varmış. Bir yokmuş.");
let ilk = roman.split('.').next().unwrap();
let a = Alinti { parca: ilk };
println!("{} {}", a.parca(), a.uzunluk());
}
Test yourself
-
What happens if <code>struct Alinti { parca: &str }</code> (without a lifetime) is written?
- parca becomes 'static
- It compiles
- parca becomes a String
- E0106: a lifetime must be specified
Show answer
E0106: a lifetime must be specified — Lifetimes aren't inferred in struct fields; either add <'a> or use an owned type like String.
-
Field with a lifetime
struct Alinti<'a> {
parca: ____,
}
Show answer
struct Alinti<'a> {
parca: &'a str,
}
-
Definition and meaning
- struct A<'a> { p: &'a str }
- Struct holding a reference
- impl<'a> A<'a>
- impl with a lifetime
- fn p(&self) -> &'a str
- Return tied to the source
- struct B { p: String }
- No lifetime needed
Next lesson: Elision rules