9.10 Structs with References and Lifetimes
9.10.1 Defining Structs with References
#![allow(unused)] fn main() { struct PersonRef<'a> { name: &'a str, age: u8, } }
- The lifetime
'a
specifies that thename
reference must live at least as long as thePersonRef
instance.
9.10.2 Using Structs with References
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 referenced data must outlive the struct instance.