rustHow to print the keys of a Rust HashMap?
You can print the keys of a Rust HashMap using the keys()
method. This method returns an iterator over the keys of the HashMap.
Example code
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
for key in map.keys() {
println!("{}", key);
}
Output example
a
b
Code explanation
use std::collections::HashMap
: imports theHashMap
type from thestd::collections
module.let mut map = HashMap::new()
: creates a new emptyHashMap
and stores it in themap
variable.map.insert("a", 1)
andmap.insert("b", 2)
: inserts two key-value pairs into themap
HashMap.for key in map.keys()
: iterates over the keys of themap
HashMap.println!("{}", key)
: prints the current key.
Helpful links
Related
- How to clone a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use an enum in a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to compare two Rust HashMaps?
- How to clear a Rust HashMap?
- How to get a reference to a key in a Rust HashMap?
- How to get all values from a Rust HashMap?
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get an element from a HashSet in Rust?
- How to declare a matrix in Rust?
- How to get the last element of a slice in Rust?
- How do I use a borrowed variable in Rust?
- How to sort the keys in a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to get the first value from a Rust HashMap?
- How to align a Rust slice to a specific size?
See more codes...