lifetime

Rust Store a borrowed field in a struct

A struct containing borrowed data usually needs a lifetime parameter for that field. The struct owns its reference, not the referenced string. Using the struct must respect the validity of that borrowed data. Expected output (not executed): Pencil: 8 Why: Product borrows name and stores its stock count by value. Common mistake: Expecting the struct to extend the life of the string it references.

Formal Syntax & Structure

rust syntaxrust
struct Record<'a> { name: &'a str }

Working Example

Example Snippetrust
struct Product<'a> { name: &'a str, stock: u32 }fn main() {    let name = String::from("Pencil");    let item = Product { name: &name, stock: 8 };    println!("{}: {}", item.name, item.stock);}
Rust Reference