Rust HashMap
In Rust, a HashMap
is a collection of key-value pairs stored in a hash table data structure. HashMap
s provide a way to quickly look up a value based on its corresponding key.
Here's an example of how to create and use a HashMap
in Rust:
use std::collections::HashMap; fn main() { // create a new HashMap with integer keys and string values let mut scores = HashMap::new(); // insert key-value pairs into the HashMap scores.insert(1, "John"); scores.insert(2, "Jane"); scores.insert(3, "Bob"); // get the value for a specific key if let Some(name) = scores.get(&2) { println!("Name of person with key 2: {}", name); } // remove a key-value pair from the HashMap scores.remove(&1); // iterate over the key-value pairs in the HashMap for (key, value) in &scores { println!("Key: {}, Value: {}", key, value); } }
In this example, we're creating a new HashMap
called scores
with integer keys and string values using the HashMap::new
constructor. We're then inserting three key-value pairs into the HashMap
using the insert
method.
We're using the get
method to retrieve the value for a specific key (2) and print it to the console using the println!
macro. We're also using the remove
method to remove the key-value pair with key 1 from the HashMap
.
Finally, we're iterating over the remaining key-value pairs in the HashMap
using a for
loop and printing each key-value pair to the console using the println!
macro.
HashMap
s can store values of any type that implements the Eq
and Hash
traits, which means you can use custom types as keys as long as you implement those traits for them. Rust also provides a HashMap::with_capacity
method for pre-allocating space for a HashMap
if you know how many key-value pairs it will contain.
HashMap
s in Rust provide a fast and efficient way to store and look up key-value pairs, making them useful in a wide range of applications.