lifetime

Rust Rust 2024 automatic lifetime capture

In Rust 2024 a free function’s opaque return type automatically captures in-scope lifetime parameters unless precise capture is specified. This may limit use of the result even when the hidden value contains no reference. For ordinary free functions in Rust 2021, a lifetime not mentioned in the return bounds was not automatically captured. Expected output (not executed): 3 Why: The result is used while the input is still alive. Common mistake: Assuming the compiler exposes the hidden usize type to the caller and thus removes all lifetime constraints.

Formal Syntax & Structure

rust syntaxrust
fn count(s: &str) -> impl std::fmt::Display

Working Example

Example Snippetrust
fn count(text: &str) -> impl std::fmt::Display { text.len() }fn main() {    let label = String::from("box");    let n = count(&label);    println!("{n}");}
Rust Reference