borrowing
Rust Borrow a read-only function argument
Choose a borrowed parameter when a function only observes its input. For text, &str is often more flexible than &String: callers can pass an owned string by reference or a string literal. Expected output (not executed): Label: Box 8 Label: Box 9 Kept: Box 8 Why: The function does not consume parcel. Deref coercion adapts &String to &str. Common mistake: Accepting String by value for a read-only operation and forcing callers to give up ownership.
Formal Syntax & Structure
rust syntaxrust
fn inspect(value: &T) { ... }Working Example
Example Snippetrust
fn show(label: &str) { println!("Label: {label}");}fn main() { let parcel = String::from("Box 8"); show(&parcel); show("Box 9"); println!("Kept: {parcel}");}