home ~ socials ~ projects ~ rss

Check If A Key Exists In A Rust BTreeMap

April 2025
use std::collections::BTreeMap;

fn main() {
  let mut items: BTreeMap<String, String> = BTreeMap::new();
  items.insert("alfa".to_string(), "this is alfa".to_string());

  // Example when it key exists
  match items.get("alfa") {
    Some(value) => println!("Got: {}", value),
    None => println!("don't have it")
  }

  // Example when it key does not exists
  match items.get("bravo") {
    Some(value) => println!("Got: {}", value),
    None => println!("don't have it")
  }

}
Output:
Got: this is alfa
don't have it
end of line
Share link:
https://www.alanwsmith.com/en/2v/jx/ws/5d/?check-if-a-key-exists-in-a-rust-btreemap