Github Add {BTreeMap,HashMap}::try_insert by m-ou-se · Pull Request #82764 · rus...
source link: https://github.com/rust-lang/rust/pull/82764
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
{BTreeMap,HashMap}::insert(key, new_val)
returns Some(old_val)
if the key was already in the map. It's often useful to assert no duplicate values are inserted.
We experimented with map.insert(key, val).unwrap_none()
(#62633), but decided that that's not the kind of method we'd like to have on Option
s.
insert
always succeeds because it replaces the old value if it exists. One could argue that insert()
is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened.
This PR adds a try_insert
method that instead returns a Result::Err
when the key already exists. This error contains both the OccupiedEntry
and the value that was supposed to be inserted. This means that unwrapping that result gives more context:
map.insert(10, "world").unwrap_none(); // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29
map.try_insert(10, "world").unwrap(); // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33
It also allows handling the failure in any other way, as you have full access to the OccupiedEntry
and the value.
try_insert
returns a reference to the value in case of success, making it an alternative to .entry(key).or_insert(value)
.
r? @Amanieu
Fixes rust-lang/rfcs#3092
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK