Why ```let v :&mut Vec<i32> = &mut vec![] ``` can live on its own?

why let v :&mut Vec<i32> = &mut vec![] can live on its own?

if you put only this line , the code compiles

who's owning this memory? when is this memory cleaned up?

Temporary lifetime extension. The drop scope is as if you had wrote

let _tmp: Vec<i32> = vec![];
let v = &mut _tmp;
3 Likes

The code itself compiling is not the most surprising thing yet. More surprising is that you can actually still use the reference after it's defined, so the Vec does live longer than a simple temporary variable limited to the duration of the let statement would. The reason why that's the case is a feature called “temporary lifetime extension”.

While it can be slightly surprising, temporary lifetime extension isn't too scary as it usually “does the right thing” or in other words, it's a slightly weird special-case rule, but a least it (generally) only affects code that would not compile otherwise anyways. And in Rust, it's already common practice to not worry about the precise ownership of things all the time, unless you start running into compilation errors (or in code where performance matters a lot).

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.