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 in pairs in Rust
- How to iterate hashset in Rust
- Rust parallel loop example
- How to loop N times in Rust
- How to iterate linked list in Rust
- How to iterate over string in Rust
- How to iterate directory recursively in Rust
- How to iterate and modify a vector in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use Unicode in a regex in Rust?
- How to split a string with Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to convert a Rust HashMap to a JSON string?
- Regex example to match multiline string in Rust?
- How to parse JSON string in Rust?
See more codes...