lifetime

Rust Return references with distinct lifetimes

Multiple output references may preserve separate input relationships. A tuple can carry each lifetime independently. This is useful when one field will be kept longer than the other. Expected output (not executed): new 42 Why: The first tuple field borrows id; only the second borrows tag. Common mistake: Collapsing the two lifetimes into one and unnecessarily restricting the first output.

Formal Syntax & Structure

rust syntaxrust
fn pair<'a, 'b>(a: &'a str, b: &'b str) -> (&'a str, &'b str)

Working Example

Example Snippetrust
fn pair<'a, 'b>(id: &'a str, tag: &'b str) -> (&'a str, &'b str) {    (id, tag)}fn main() {    let id = String::from("42");    let kept;    {        let tag = String::from("new");        let (a, b) = pair(&id, &tag);        println!("{b}");        kept = a;    }    println!("{kept}");}
Rust Reference