rustHow to pass a Rust HashMap as an argument?
Passing a Rust HashMap as an argument is done by using the & operator. This operator allows the HashMap to be passed by reference, meaning that the original HashMap is not copied.
Example code
fn print_map(map: &HashMap<String, i32>) {
for (key, value) in map {
println!("{}: {}", key, value);
}
}
fn main() {
let mut map = HashMap::new();
map.insert("one".to_string(), 1);
map.insert("two".to_string(), 2);
print_map(&map);
}
Output example
one: 1
two: 2
Code explanation
fn print_map(map: &HashMap<String, i32>): This is the function declaration, which takes a reference to a HashMap as an argument.for (key, value) in map: This loop iterates over the HashMap, allowing each key-value pair to be accessed.println!("{}: {}", key, value);: This prints the key-value pair to the console.let mut map = HashMap::new();: This creates a new, empty HashMap.map.insert("one".to_string(), 1);: This inserts a key-value pair into the HashMap.print_map(&map);: This passes the HashMap to theprint_mapfunction.
Helpful links
Related
- How to create a HashMap of structs in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to print a Rust HashMap?
- How to lock a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to convert a Rust HashMap to JSON?
- How to compare two Rust HashMaps?
- How to sort a Rust HashMap?
- How to clear a Rust HashMap?
More of Rust
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use regex to match a double quote in Rust?
- Regex example to match multiline string in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex lookbehind in Rust?
- How to match a URL with a regex in Rust?
- How to match the end of a line in a Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to clear a Rust HashMap?
See more codes...