Why does BTreeSet::clear have constraint A:Clone?

I think this is just a minor mistake, or there is something I don’t understand. The corresponding clear function in BTreeMap doesn’t have it.

BTreeMap has the same bound; it's just on the impl instead of the fn. Note that this is a constraint on the allocator, not the key or value.

2 Likes

Here's the BTreeMap::clear function's docs; you can see the Clone bound shortly above. As for why, here's the source code: map.rs - source. Essentially, it replaces &mut self with a new empty BTreeMap and drops the old one. (The allocator is cloned to create the new BTreeMap. The cloning isn't strictly necessary AFAIK, just simplifies the code.)

So, TIL that BTreeMap::clear doesn't reuse capacity, though maybe I should have expected that.

1 Like

I see now, it is an implementation detail, and I think slightly confusing for stupid people such as myself!

BTreeMap doesn't even have a concept of "capacity".

As in, one might hope that the node allocations could be reused. (The implementation of BTreeMap is already complicated enough, though, and that concern could be addressed with the allocator API; there could be an allocator custom-made for improving the performance of BTreeMap.)

My BTreeMap has a trait that allows the BTreeMap performance to be “tuned”, either for speed or memory consumption. Also it can be temporarily set to be optimised for ordered insertion.