rustHow to use a generator map in Rust?
Using a generator map in Rust is a great way to create a map of values from an iterator. It is similar to the map
method, but instead of returning a new iterator, it returns a HashMap
.
Example code
let v = vec![1, 2, 3];
let m: HashMap<_, _> = v.into_iter().map(|x| (x, x * x)).collect();
Output example
{1: 1, 2: 4, 3: 9}
Code explanation
-
let v = vec![1, 2, 3];
: This creates a vector with the values 1, 2, and 3. -
let m: HashMap<_, _> =
: This creates aHashMap
with the type of the keys and values left unspecified. -
v.into_iter().map(|x| (x, x * x))
: This creates an iterator from the vectorv
and maps each value to a tuple of the value and its square. -
collect()
: This collects the iterator into aHashMap
.
Helpful links
Related
More of Rust
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to split a string with Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to parse JSON string in Rust?
- How to use a tuple as a key in a Rust HashMap?
See more codes...