I have an owned object, and I want to move it into a hash set, but also get an immutable reference to that item in the hash set.
This seems like a perfect use case for the get_or_insert function, but this is apparently only experimental, and I would like to keep my codebase on the stable branch if possible.
I wish I could just insert the item, and then call .get(ITEM).unwrap() but I can't because the item has been moved into the hashset.
Is there a way of doing this that I'm not thinking of?
#Insert item into hash set and get reference to it
1 messages · Page 1 of 1 (latest)
entry and or_insert
my bad, thought you were talking about hashmap
Yeah that seems like it should be possible but isn't. Kinda weird.
I think the simplest solution is to add hashbrown as a dependency and use that get_or_insert. It's the same as std's but you don't need nightly.
Interesting I didn't know about that
Looks like it also brings performance improvements, I might switch to that outright
It's the same. It's what the std library uses.
Technically it is, but you have to manually match on the entry
match map.entry(key) {
Entry::Vacant(v) => v.insert(value),
Entry::Occupied(o) => o.into_mut(),
}
Oh wait
it claims on the github to be 2x faster than the standard library implementation
Oh I see so the rust standard library uses hashbrown now, and its 2x faster than what the standard library used to use
That makes sense
Oh and hashbrown::HashSet has entry!
Hashbrown is basically "hey, I would like all of the cool APIs std doesn't yet have thanks"
Gotcha
... but or_insert doesn't return a reference to it.