最小复制:
fn main() {
use std::collections::HashMap;
use std::iter::FromIterator;
let _ = HashMap::from_iter([("key", "value")].iter());
}
您必须迭代拥有的元组,而不是借用的元组,因此会出现奇怪的错误消息:
fn main() {
use std::collections::HashMap;
use std::iter::FromIterator;
let _: HashMap<_, _> = HashMap::from_iter([("key", "value")].iter().cloned());
}
您还可以使用collect
正如文档中所述FromIterator
:
FromIterator
's from_iter
很少显式调用,而是通过以下方式使用Iterator
's collect
方法。看collect
的文档以获取更多示例。
fn main() {
use std::collections::HashMap;
let _: HashMap<_, _> = [("key", "value")].iter().cloned().collect();
// or
let _: HashMap<_, _> = vec![("key", "value")].into_iter().collect();
}
请注意,错误消息更容易理解collect
:
error[E0277]: the trait bound `std::collections::HashMap<_, _>: std::iter::FromIterator<&(&str, &str)>` is not satisfied
--> src/main.rs:4:54
|
4 | let _: HashMap<_, _> = [("key", "value")].iter().collect();
| ^^^^^^^ a collection of type `std::collections::HashMap<_, _>` cannot be built from an iterator over elements of type `&(&str, &str)`
|
= help: the trait `std::iter::FromIterator<&(&str, &str)>` is not implemented for `std::collections::HashMap<_, _>`
最后一行更有帮助:迭代器必须迭代元组而不是对元组的引用:
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>