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.
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).