Home
Rust
map Examples
Updated 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.
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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 8, 2023 (edit link).
Home
Changes
© 2007-2025 Sam Allen