lifetime

Rust Express an outlives relationship

A lifetime bound written 'long: 'short states that the first region includes the second. It can justify returning a longer-lived shared reference using a shorter lifetime required by an API. It does not delay a destructor. Expected output (not executed): Ada Why: The bound allows the returned reference to be used with the context lifetime. Common mistake: Reading the colon backwards or expecting the bound to extend the lifetime of context.

Formal Syntax & Structure

rust syntaxrust
fn shorten<'long: 'short, 'short>(x: &'long str, marker: &'short str) -> &'short str

Working Example

Example Snippetrust
fn for_context<'long: 'short, 'short>(name: &'long str, _context: &'short str) -> &'short str {    name}fn main() {    let name = String::from("Ada");    {        let context = String::from("session");        println!("{}", for_context(&name, &context));    }}
Rust Reference