Struct lifetimes
- Rust course
- Intermediate
- Lesson 16/115
- 4 min
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
}
}Practice 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.
Starter code
fn main() {
// buraya yaz
}Sample 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());
}Expected output
Bir varmış 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: Lifetimes aren't inferred in struct fields; either add <'a> or use an owned type like String.
2 Field with a lifetime
struct Alinti<'a> {
parca: ____,
}
struct Alinti<'a> {
parca: &'a str,
}
Explanation: The reference field is marked with the struct's lifetime parameter.
3 Definition and meaning
| Term | 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 |