Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Crate {
- pub weight: f64,
- }
- /*
- Rust can handle memory management on it's own.
- However, Rust doesn't know how long a reference should live in a struct.
- The reference may also depend on other references, etc.
- Therefore we must let the compiler know how long the reference should live.
- This is done with the 'lifetime specifiers'/'lifetime parameters'.
- Applying it to Truck and to Truck::crates tells the compiler "Hey compiler! Each Crate reference depends on Truck! Kill the Crates only if the Truck dies!"
- You can manually test this behaviour by manually calling Truck's destructor via 'drop(truck)'
- */
- struct Truck<'a> {
- pub crates: Vec<&'a Crate>,
- }
- fn main() {
- let c1 = Crate { weight: 10.0 };
- let c2 = Crate { weight: 9.5 };
- let truck = Truck { crates: vec![&c1, &c2] };
- for c in truck.crates {
- println!("{:?}", c.weight);
- }
- }
Add Comment
Please, Sign In to add comment