lifetime

Rust Return either borrowed input

When a function may return either reference, a common lifetime parameter can express a guarantee valid for whichever branch runs. The caller must support a common usable region for both arguments. Their owners need not have identical scopes. Expected output (not executed): South Why: Both inputs are valid during the result use inside the inner block. Common mistake: Assuming a runtime branch selecting primary guarantees that the return type can outlive backup.

Formal Syntax & Structure

rust syntaxrust
fn choose<'a>(a: &'a str, b: &'a str, flag: bool) -> &'a str

Working Example

Example Snippetrust
fn choose<'a>(primary: &'a str, backup: &'a str, use_backup: bool) -> &'a str {    if use_backup { backup } else { primary }}fn main() {    let primary = String::from("North");    {        let backup = String::from("South");        println!("{}", choose(&primary, &backup, true));    }}
Rust Reference