Skip to content

implement BTreeMap::merge#151981

Closed
asder8215 wants to merge 7 commits into
rust-lang:mainfrom
asder8215:btreemap_append_with
Closed

implement BTreeMap::merge#151981
asder8215 wants to merge 7 commits into
rust-lang:mainfrom
asder8215:btreemap_append_with

Conversation

@asder8215
Copy link
Copy Markdown
Contributor

@asder8215 asder8215 commented Feb 2, 2026

This PR implements BTreeMap::append_with() as mentioned in #147700 (and discussed by the forum post linked in the issue). I'm not sure if the issue made is an approval for this feature, but regardless I'm going to make an ACP soon. I decided to made a small change to the API for append_with than the one proposed by @nagisa:

pub fn append_with(&mut self, other: &mut BTreeMap<K, V, A>, conflict: impl FnMut(&K, V, V) -> V);

I think having the conflict function own self's value and returning an owned value might give a lot more flexibility to the user. It also feels a bit more intuitive to me as the user that a value of type V is being put into self when there's conflicting keys between self and other.

For example, if my values are String types and I want to combine my values when keys are conflicting, then they can either mutate selfs value with .push_str() passing in other's value and return self's value, or they can use format!() to return a concatenation of self's and other's value.

Now, a consequence for this approach is that it's very well possible that the user decides to return a value V that has nothing to do with self or other when it comes to a conflicting key. However, should we decide to do conflict: impl FnMut(&K, &mut V, V), I could have mutated self's value easily to produce a whole different value that has nothing to do with the original value of self or other.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-ACP Status: PR has an ACP and is waiting for the ACP to complete. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants