In programming languages, the term "map" means 2 things. A map function can apply a transformation to each element in an array.
The other use of "map" refers to a dictionary collection. In Rust, we have both kinds of map, but the dictionary is called a HashMap
.
In this example we use the iter()
function to get an iterator from an array. We then invoke the map()
function to uppercase all strings.
iter()
to get an iterator from the animals array. We pass a lambda to map()
, and make each string
uppercase.for
-loop over the result of map()
to loop over the strings, and print them to the console. All strings are now uppercase.fn main() { let animals = ["bird", "frog", "cat"]; // Part 1: use iter() map to uppercase all strings. let result = animals.iter().map(|value| value.to_uppercase()); // Part 2: loop over strings and print them. for animal in result { println!("MAP: {}", animal); } }MAP: BIRD MAP: FROG MAP: CAT
A "map" is a dictionary as well. Here we create a HashMap
, and use that as our map. The HashMap
stores optional values, and we can unwrap
them.
match()
construct in Rust to unwrap
values returned by get()
on a HashMap
.use std::collections::HashMap; fn main() { // Create HashMap to map keys to values. let mut codes = HashMap::new(); codes.insert("abc", 1); codes.insert("def", 2); // Access value with get function. println!("{:?}", codes.get("abc")); }Some(1)
How can we use various types of map()
functionality in Rust? The answer is clear. We can use iter()
and map()
to translate elements, and a HashMap
for an associative array.