Guest User

Untitled

a guest
Feb 17th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. struct Crate {
  2. pub weight: f64,
  3. }
  4.  
  5. /*
  6. Rust can handle memory management on it's own.
  7. However, Rust doesn't know how long a reference should live in a struct.
  8. The reference may also depend on other references, etc.
  9. Therefore we must let the compiler know how long the reference should live.
  10. This is done with the 'lifetime specifiers'/'lifetime parameters'.
  11. 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!"
  12. You can manually test this behaviour by manually calling Truck's destructor via 'drop(truck)'
  13. */
  14. struct Truck<'a> {
  15. pub crates: Vec<&'a Crate>,
  16. }
  17.  
  18. fn main() {
  19. let c1 = Crate { weight: 10.0 };
  20. let c2 = Crate { weight: 9.5 };
  21. let truck = Truck { crates: vec![&c1, &c2] };
  22. for c in truck.crates {
  23. println!("{:?}", c.weight);
  24. }
  25. }
Add Comment
Please, Sign In to add comment