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_map
function.
Helpful links
Related
- How to use a tuple as a key in a Rust HashMap?
- How to implement PartialEq for a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to create a HashMap of traits in Rust?
- How to create a HashMap of HashMaps in Rust?
More of Rust
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...