Insert an Item into a Vec Inside a BTreeMap in Rust
December 2025
One pattern I hit frequently is needing to loop through a batch of content to categories groups of content by a key. This is how I'm doing it in Rust using a BTreeMap to store Vecs associated with a key.
The add_to_vec function will create a new item if necessary or add the incoming item to the existing keys vec:
use BTreeMap;
Output:
[_active_nvim_run:10:3] items = {
"alfa": [
"the",
"quick",
],
"bravo": [
"brown",
"fox",
],
}
I wouldn't be surprised if there's other data structures that handle this. If I find one, I'll use it. This work fine in the mean time.
-a
end of line
References
It's like a Hash, but it keeps the order.