rustHow to build a Rust HashMap from an iterator?
To build a Rust HashMap from an iterator, you can use the collect()
method. This method takes an iterator and collects its elements into a collection. For example, the following code creates a HashMap from an iterator of tuples:
let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].iter().collect();
The output of this code is:
{1: "a", 2: "b", 3: "c"}
The code consists of the following parts:
let map: HashMap<_, _>
: This declares a variablemap
of typeHashMap
with generic type parameters_
and_
.[(1, "a"), (2, "b"), (3, "c")]
: This is an array literal containing tuples of integers and strings..iter()
: This converts the array into an iterator..collect()
: This collects the elements of the iterator into a collection.
Helpful links
Related
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to convert a Rust HashMap to a struct?
- How to use a custom hash function with a Rust HashMap?
- How to clone a Rust HashMap?
- How to use a custom hasher with a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to compare two Rust HashMaps?
More of Rust
- How to parse JSON string in Rust?
- How to yield return in Rust?
- How to replace strings using Rust regex?
- How to convert a slice of bytes to a string in Rust?
- How to modify an existing entry in a Rust HashMap?
- How do I get the last character from a string in Rust?
- How to escape dots with regex in Rust?
- How to get a value by key from JSON in Rust?
- How to use named capture groups in Rust regex?
- How to convert struct to JSON string in Rust?
See more codes...