How to check if key exists in HashMap in Rust

Created
Modified

Using HashMap::contains_key Method

The contains_key method return true if the map contains a value for the specified key.

use std::collections::HashMap;

fn main() {
  let mut map = HashMap::new();
  map.insert("name", "John");

  println!("{}", map.contains_key("name"))
}
true

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

Numeric Keys Example,

use std::collections::HashMap;

fn main() {
  let mut map = HashMap::new();
  map.insert(1, "age");

  println!("{}", map.contains_key(&6));
  println!("{}", map.contains_key(&1));
}
false
true

Using the Eq Trait

If you cannot use the derive strategy, specify that your type implements Eq, which has no methods:

use std::collections::HashMap;
use std::hash::{Hash, Hasher};

struct Book {
  isbn: i64,
  title: String,
}

impl Hash for Book {
  fn hash(&self, state: &mut H) {
    self.isbn.hash(state);
    // self.title.hash(state);
  }
}
impl PartialEq for Book {
  fn eq(&self, other: &Self) -> bool {
    self.isbn == other.isbn
  }
}
impl Eq for Book {}

fn main() {
  let mut map: HashMap = HashMap::new();
  map.insert(
    Book {
      isbn: 1,
      title: "Apple".to_string(),
    },
    "Book".to_string(),
  );

  // true
  let key = Book {
    isbn: 1,
    title: "Google".to_string(),
  };
  println!("{}", map.contains_key(&key));

  // false
  let key2 = Book {
    isbn: 2,
    title: "Google".to_string(),
  };
  println!("{}", map.contains_key(&key2));
}
true
false

Related Tags

#check# #key# #HashMap#