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 std::collections::BTreeMap;

fn main() {
  let mut items: BTreeMap<String, Vec<String>> = 
    BTreeMap::new();
  add_to_vec("alfa", "the", &mut items);
  add_to_vec("alfa", "quick", &mut items);
  add_to_vec("bravo", "brown", &mut items);
  add_to_vec("bravo", "fox", &mut items);
  dbg!(items);
}

fn add_to_vec(
    key: &str, 
    item: &str, 
    items: &mut BTreeMap<String, Vec<String>>
  ) {
  if let Some(v) = items.get_mut(key) {
    v.push(item.to_string());
  } else {
    items.insert(
      key.to_string(), 
      vec![item.to_string()]
    );
  }
}
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.