The problem is that if you look into other languages you will see that:
- on a hash map insertion the old value is returned (or null/none/…)
- on a hash set insertion either
- nothing is returned at all
-
true is returned if the length of the hash map changed/
the value was “new”
So changing this would be confusing for everyone being used to
other map/set implementations.
Also you semantically always insert a value into a has set, the question is just if the length of the set changes. I.e. if the value
was new.
@scottmcm: wouldn’t this try_insert be more or less a entry api?
Also you can’t get mutable access to a hash sets item (or an
hash maps key) as this would allow you to change the item,
which would change the hash, which in turn would require
the set to run some code (calculating the new hash, potentially
reducing the length by 1 if it now is equal to another item).
This can’t be done when returning a &mut T.
What could work is something like:
fn entry(&mut self, value: T) -> Entry<T>
with:
impl<'a, T> Entry<'a, T> {
fn is_new(&self) -> bool {
self.external().is_none()
}
/*[EDIT]: this method has a number of conceptual problems
implementing a &mut T, method on a standard HashSet turns
out to be a bad idea (in the general case)
fn modify<FN, R>(func: FN) -> R
where FN: FnOnce(&mut T) -> R
{...}
*/
fn external(&self) -> Option<&T> { ... }
fn external_mutl(&mut self) -> Option<&mut T> { ... }
}
// equiv. to get (but this means a Entry has two fields,
// 1st a reference to the now contained value, 2nd an
// option with the not used new value, we probably might
// not want to return a reference to the second value here
// for the case it is not exactly the same wrt. side-effects even
// through it should, or we do so make entry an enum and
// document the potential problem?)
impl<'a, T> Borrow<T> for Entry<'a, T> { ... }
//maybe also add a `fn into_external_value()` to Entry
impl<'a, T> Into<Option<T>> for Entry<'a, T> { ... }
(omitted some bounds on T)
(API would need some more consideration wrt. turning a Entry
into the opt. external value)