rustHow to iterate btreemap in Rust
Iterating over a BTreeMap
in Rust can be done using the iter()
method. This method returns an iterator over the entries of the map, which can then be used to access the key-value pairs.
Example code
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert("a", 1);
map.insert("b", 2);
for (key, value) in map.iter() {
println!("key: {} value: {}", key, value);
}
Output example
key: a value: 1
key: b value: 2
Code explanation
use std::collections::BTreeMap;
: imports theBTreeMap
type from thestd::collections
module.let mut map = BTreeMap::new();
: creates a new emptyBTreeMap
.map.insert("a", 1);
: inserts a key-value pair into theBTreeMap
.for (key, value) in map.iter() {
: starts an iterator loop over the entries of theBTreeMap
.println!("key: {} value: {}", key, value);
: prints the key and value of the current entry.
Helpful links
Related
- How to loop until error in Rust
- How to iterate linked list in Rust
- How to iterate over string in Rust
- How to iterate a map in Rust
- Rust for loop range inclusive example
- How to do a for loop with index in Rust
- How to iterate in pairs in Rust
- How to loop N times in Rust
- Rust negative for loop example
- Rust parallel loop example
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...