RRust By Example
advancedLifetimes

Lifetime Bounds

Use lifetime bounds in generic contexts.

Lifetime Bounds

Use lifetime bounds in generic contexts.

Difficulty

Advanced

Code

rust
use std::fmt::Display;

fn longest_with_announcement<T: Display>(x: &str, y: &str, ann: T) -> &str {
    println!("Announcement: {}", ann);
    if x.len() > y.len() { x } else { y }
}

struct Wrapper<T> {
    value: T,
}

impl<T: Display> Wrapper<T> {
    fn new(value: T) -> Self {
        Wrapper { value }
    }

    fn display(&self) {
        println!("value: {}", self.value);
    }
}

fn main() {
    let s1 = String::from("long string");
    let s2 = String::from("xyz");
    let result = longest_with_announcement(&s1, &s2, "comparing strings");
    println!("longest: {}", result);

    let num = 42;
    let w = Wrapper::new(num);
    w.display();
}

Explanation

Lifetime bounds constrain generics: T: Display + 'a.

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.

More Lifetimes Examples