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?
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 beforemap. 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.
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.