Construction ordering affects lifetime?


#1

I’m having a strange error with object lifetime that seems dependent on variable initialization order. A minimal example is available here.

Pseudocode summary:
// Works let mut list = Vec::new(); let mut map = HashMap::New() use_objects(&list, &mut map); // // Gives lifetime error for 'list' when declared in the reverse order let mut map = HashMap::New() let mut list = Vec::new(); use_objects(&list, &mut map);

If this is a valid error, could someone explain why the ordering matters?


#2

The actually important part is the signature:

fn print_lists<'a>(list: &'a Vec<String>, map: &mut HashMap<&'a str, u16>)

This says that the lifetime of the pointer to the Vec, and the lifetime of the pointers being stored in the HashMap must be at least the same.

The problem with the second block is that local variables are destroyed in reverse lexical order, meaning list will be destroyed before map. If the call passed the borrow-checker, it would be possible to store a pointer to list inside map. This would be bad, because when map gets destroyed, it would contain an accessible pointer to the now-invalid list variable.


#3

Hm, that makes sense, is that documented somewhere?


#4

I think it sort of follows from the description of lifetimes in the rustonomicon, but I haven’t seen it anywhere in the more beginner-focussed documentation.


#5

https://doc.rust-lang.org/book/drop.html