RRust By Example
advancedLifetimes

Lifetime in Structs

Use lifetimes in struct definitions.

Lifetime in Structs

Use lifetimes in struct definitions.

Difficulty

Advanced

Code

rust
#[derive(Debug)]
struct Excerpt<'a> {
    text: &'a str,
}

impl<'a> Excerpt<'a> {
    fn level(&self) -> i32 {
        3
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("no period");
    let excerpt = Excerpt { text: first_sentence };
    println!("{:?}", excerpt);
    println!("level: {}", excerpt.level());
}

Explanation

Structs with references need lifetime annotations.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the lifetimes category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Lifetimes Examples