lifetime

Rust Use the anonymous lifetime placeholder

The placeholder '_ requests lifetime inference in positions that support it. In a returned struct type it makes the presence of a borrowed lifetime visible, even though its relationship can be inferred from the signature. Expected output (not executed): ready Why: The one input lifetime determines the borrowed lifetime in View. Common mistake: Expecting '_ to resolve an ambiguous two-input return relationship or using it as a declared generic name.

Formal Syntax & Structure

rust syntaxrust
fn view(s: &str) -> View<'_>

Working Example

Example Snippetrust
struct View<'a>(&'a str);fn view(s: &str) -> View<'_> {    View(s.trim())}fn main() {    let text = String::from("  ready ");    let v = view(&text);    println!("{}", v.0);}
Rust Reference