Home
Rust
map Examples
This page was last reviewed on Feb 8, 2023.
Dot Net Perls
Map. In programming languages, the term "map" means 2 things. A map function can apply a transformation to each element in an array.
Shows a map
Collections. 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.
collect
Map function. 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.
Part 1 We call iter() to get an iterator from the animals array. We pass a lambda to map(), and make each string uppercase.
iter
Part 2 We use a for-loop over the result of map() to loop over the strings, and print them to the console. All strings are now uppercase.
for
Shows a map
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
Map collection. 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.
HashMap
Tip Try using the match() construct in Rust to unwrap values returned by get() on a HashMap.
match
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)
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 8, 2023 (edit link).
Home
Changes
© 2007-2024 Sam Allen.