What Is Lifetime Subtyping in Rust?

Lifetime subtyping ensures references are valid by enforcing that longer lifetimes can be used where shorter lifetimes are expected.

Lifetime subtyping in Rust is the compiler's enforcement that a reference's lifetime must be at least as long as any other lifetime it is used with, ensuring memory safety without garbage collection. The borrow checker uses this rule to prevent dangling references by verifying that a longer-lived reference can be safely treated as a shorter-lived one, but not vice versa.

fn longest<'a, 'b: 'a>(x: &'a str, y: &'b str) -> &'a str {
    // 'b must outlive 'a, so we can return x safely
    x
}

This constraint 'b: 'a means the lifetime 'b is a subtype of 'a (it lives longer), allowing the function to return a reference with the shorter lifetime 'a.