Created
February 5, 2018 09:55
-
-
Save ioncodes/5f10da3ae145a2c1c6f2bbede14622c5 to your computer and use it in GitHub Desktop.
Small explanation how lifetimes work for @mortoray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment