Retrieve a reference type key from a HashMap

Hi all,
Is the code below a proper way to retrieve an original key from a HashMap?
In a few derived HashMaps, I use references to keys living in a mother HashMap. Just creating a ref to a newly created key-value does not work because it goes out of scope in no time: this does not work:

{
     ...
     auxmap.insert(&Location::new(value_x, value_y), newValue)
     ...
}

This compiles (reduced code):

{
     ...
     let  key = *auxmap.get_key_value(&Location::new(value_x, value_y)).unwrap().0;  
     auxmap.insert(key, newValue);
     ...
}

Is this remotely idiomatic?
Is HashMap::entry() the way to go, knowing my key exists? entry() seems to be meant for use cases where key existence is not known in advance.
Should I just use clones of the key values (Location {x: i32, y: i32}) and thus avoid this problem?

Thanks.

Since Location consists of just 2 i32 I would for sure go for clones. I would even derive Copy for it since it is really small. For comparison, a Location should occupy exactly as much memory as a &Location on a 64 bit machine, so you're only complicating your life if you're storing &Location

4 Likes

Perfect. I tried to derive Copy before, missing the point that Clone must then be derived as well.
Using Location as a key (not &Location) I can just overwrite the current value with

auxmap.insert(Location::new(x,y), newvalue);

and do not need the get_key_value().unwrap().0 construction any more.
Thanks.