implement append_with() for BTreeMap #151981
Open
+132
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 forappend_withthan the one proposed by @nagisa:I think having the
conflictfunction ownself'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 typeVis being put intoselfwhen there's conflicting keys betweenselfandother.For example, if my values are
Stringtypes and I want to combine my values when keys are conflicting, then they can either mutateselfs value with.push_str()passing inother's value and returnself's value, or they can useformat!()to return a concatenation ofself's andother's value.Now, a consequence for this approach is that it's very well possible that the user decides to return a value
Vthat has nothing to do withselforotherwhen it comes to a conflicting key. However, should we decide to doconflict: impl FnMut(&K, &mut V, V), I could have mutatedself's value easily to produce a whole different value that has nothing to do with the original value ofselforother.