How do I create a map from a list in a functional

2019-03-24 07:55发布

问题:

In Scala, there is a method named toMap that works on any list of tuples and converts it to a map where the key is the first item on the tuple and the value is the second one:

val listOfTuples = List(("one", 1), ("two", 2))
val map = listOfTuples.toMap 

What is the closest thing to toMap in Rust?

回答1:

Use Iterator::collect:

use std::collections::HashMap;

fn main() {
    let tuples = vec![("one", 1), ("two", 2), ("three", 3)];
    let m: HashMap<_, _> = tuples.into_iter().collect();
    println!("{:?}", m);
}

collect leverages the FromIterator trait. Any iterator can be collected into a type that implements FromIterator. In this case, HashMap implements it as:

impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where
    K: Eq + Hash,
    S: HashState + Default,

Said another way, any iterator of tuples where the first value can be hashed and compared for total equality can be converted to a HashMap. The S parameter isn't exciting to talk about, it just defines what the hashing method is.

See also:

  • Collect iterators of length 2 into HashMap


标签: rust