Add all items from an immutable set to a mutable set with minimal cloning

I have mut foo: BTreeSet<T> and bar: &BTreeSet<T>. I want to add all items from bar to foo without cloning items that already exist in foo. What's the best way to do it?

BTreeSet implements Extend to add items from an iterator. You’ll need to clone the items coming from bar (because it’s immutable), which you can do with Iterator::cloned. Putting it all together, you should be able to do something like (untested):

foo.extend(bar.iter().cloned());

That will call clone more than necessary, since it clones each item in bar before trying to insert it.

This version has minimal cloning, at the expense of doing more tree traversals:

    for x in bar {
        if !foo.contains(x) {
            foo.insert(x.clone());
        }
    }
2 Likes

Note: Doing this more efficiently, without the redundent tree traversal, would require BTreeSet to gain an API similar to the experimental HashMap::raw_entry_mut.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.