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