Consider the following Rust function:
enum MyType {One, Two}
fn example<'a>() -> &'a MyType {
let t = MyType::Two;
return &t;
}
It clearly fails to compile and produces an appropriate warning, as I attempted to return a reference to a value that goes out of scope at the end of the function and consequently gets freed.
However, if I instead "merge" the two statements into one, i.e. I use the & operator right before an instance of MyType::Two, it compiles without any errors:
fn example<'a>() -> &'a MyType {
return &(MyType::Two);
}
I do understand why the following works:
fn example() -> &'static MyType {
return &(MyType::Two);
}
By annotating the return type of the function with the static lifetime I am telling the compiler that there will always exist an instance of MyType::Two in memory that will be valid for the entire duration of the program.
My question then is:
- Why does the example in the second code block compile? What information does the compiler gain by me annotating the return type with the generic
alifetime that allows it to guarantee that the reference toMyType::Twowill be valid by the time the function returns?
(this makes no sense to me as I have used the generic 'a lifetime parameter and not 'static)