What Are Lifetime Bounds on Generic Types?

Lifetime bounds on generic types are constraints ensuring references remain valid for the required duration to prevent memory safety errors.

Lifetime bounds on generic types are constraints that specify how long a reference must remain valid relative to other references in a function or struct. You define them using the 'a syntax in the generic parameter list to ensure the compiler can verify memory safety.

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

In this example, the 'a lifetime bound ensures the returned reference lives as long as the shortest of the two input references.