rust iterate over Hashmap
The for
loop is a convenient way to iterate over the key-value pairs of a HashMap
in Rust. It allows you to write a loop that will execute a block of code for each key-value pair in the HashMap
.
Here's the general syntax for a for
loop in Rust:
rust iterate over Hashmap
for variable in iterable { code to execute }
In the case of a HashMap
, the iterable
is obtained by calling the .iter()
method on the HashMap
, and variable
is a tuple containing a reference to the key and a reference to the value.
To iterate over the key-value pairs of a HashMap
in Rust, you can use a for
loop with the .iter()
method. Here's an example:
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for (key, value) in map.iter() { println!("{}: {}", key, value); } }
This will print the key-value pairs like this:
a: 1 b: 2 c: 3
You can also use the into_iter()
method to iterate over the key-value pairs and move them out of the HashMap
. This is useful if you want to take ownership of the key-value pairs and store them elsewhere:
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); let pairs: Vec<(String, i32)> = map.into_iter().collect(); for (key, value) in pairs { println!("{}: {}", key, value); } }
This will print the key-value pairs in the same way as the previous example, and the map
variable will be empty after the loop.