9.9 Structs with References and Lifetimes
9.9.1 Defining Lifetimes
#![allow(unused)] fn main() { struct PersonRef<'a> { name: &'a str, age: u8, } }
9.9.2 Using Lifetimes in Practice
struct PersonRef<'a> { name: &'a str, age: u8, } fn main() { let name = String::from("Henry"); let person = PersonRef { name: &name, age: 50, }; println!("Name: {}, Age: {}", person.name, person.age); }
The name
variable must outlive the PersonRef
instance so the reference remains valid.