borrowing

Rust Return a view of caller-owned data

A function may return a borrow of an input that remains valid. With one reference input, the usual lifetime-elision rule relates the output lifetime to that input. If the function creates a fresh local String, return the owned String instead of a view of its soon-to-be-dropped contents. Expected output (not executed): INV / INV-42 Why: The returned slice refers to code, which is still owned by the caller. This example assumes at least three bytes and a UTF-8 boundary at byte three. Common mistake: Using &local_string as a return value or slicing arbitrary UTF-8 by unchecked byte positions.

Formal Syntax & Structure

rust syntaxrust
fn select(input: &str) -> &str { ... }

Working Example

Example Snippetrust
fn prefix(text: &str) -> &str {    &text[..3]}fn main() {    let code = String::from("INV-42");    println!("{} / {code}", prefix(&code));}
Rust Reference