lifetime

Rust Single-input lifetime elision

For an ordinary function with one input lifetime, an omitted output lifetime is associated with that input. Other arguments that contain no references do not introduce input lifetimes. Elision keeps straightforward signatures readable. Expected output (not executed): INV Why: The returned slice refers to code. get avoids panicking if the requested byte boundary is invalid. Common mistake: Assuming n introduces another lifetime, or assuming a byte index is always a character boundary.

Formal Syntax & Structure

rust syntaxrust
fn first_word(s: &str) -> &str

Working Example

Example Snippetrust
fn prefix(s: &str, n: usize) -> &str {    s.get(..n).unwrap_or(s)}fn main() {    let code = String::from("INV-42");    println!("{}", prefix(&code, 3));}
Rust Reference