lifetime

Rust Tie the output only to the selected input

An output can be related to one input and independent of another. Express only the borrowing relationship required by the implementation. This permits callers to keep the result even after unrelated input data is dropped. Expected output (not executed): Note: verified Ada Why: The return type is tied to name, not note. Common mistake: Using the same lifetime for both inputs even though only one can be returned.

Formal Syntax & Structure

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

Working Example

Example Snippetrust
fn primary<'a>(name: &'a str, note: &str) -> &'a str {    println!("Note: {note}");    name}fn main() {    let name = String::from("Ada");    let chosen;    {        let note = String::from("verified");        chosen = primary(&name, &note);    }    println!("{chosen}");}
Rust Reference