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 implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to create a new Rust HashMap with values?
- How to convert a Rust HashMap to JSON?
- How to remove an element from a Rust HashMap if a condition is met?
- How to create a HashMap of pointers in Rust?
- How to compare two Rust HashMaps?
- How to sort a Rust HashMap?
- How to create a new Rust HashMap with a specific type?
More of Rust
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to get an entry from a HashSet in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to get all values from a Rust HashMap?
- How to modify an existing entry in a Rust HashMap?
- How to calculate the sum of a Rust slice?
See more codes...