(I am having trouble grasping lifetimes and ownership in Rust)
Consider the following Rust struct
definition:
struct MyType<'lifetime> {
one: &'lifetime u32,
two: &'lifetime u32
}
My current interpretation of the above definition is as follows:
I have defined a
struct MyType
. The<'lifetime>
next to its identifier refers to a specific lifetime of any one instance ofMyType
. The fieldsone
andtwo
are references tou32
s, and because they are annotated with'lifetime
, the integers that they refer to are guaranteed to live at least as long as the instance of the struct they belong to.
To challenge my current understanding I created this example:
fn main() {
let num1: u32 = 11;
let instance: MyType;
{ // nested scope
let num2: u32 = 22;
instance = MyType {
one: &num1,
two: &num2
};
println!("{:?}", instance);
}
}
This code compiles and runs (printing MyType { one: 11, two: 22 }
), but it seems to disprove my understanding:
As instance
gets dropped at the end of main
1 and num2
gets dropped at the end of the nested scope right before it, my initial understanding seems false: the integer referred to by the two
field didn't live "at least as long as the struct instance".
Where am I wrong? What does the 'lifetime
in struct MyType<'lifetime'>
actually refer to?
1: I am also unsure if this is correct.