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

This example demonstrates how to use lifetime in structs in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Lifetimes Examples