此代码有效:
use std::collections::HashMap;
fn main() {
let result: HashMap<&str, &str> = [("name", "Luke")].iter().cloned().collect();
println!("{:?}", &result);
}
如果我删除了对cloned()
的调用
error[E0277]: the trait bound `std::collections::HashMap<&str, &str>: std::iter::FromIterator<&(&str, &str)>` is not satisfied
--> src/main.rs:4:65
|
4 | let result: HashMap<&str, &str> = [("name", "Luke")].iter().collect();
| ^^^^^^^ a collection of type `std::collections::HashMap<&str, &str>` 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<&str, &str>`
我的理解是标准库为元组实现了很多东西,但不是这种情况?为什么不编译呢?
答案 0 :(得分:3)
完整的错误消息包含更多有用的信息:
error[E0277]: the trait bound `std::collections::HashMap<&str, &str>: std::iter::FromIterator<&(&str, &str)>` is not satisfied
--> src/main.rs:4:65
|
4 | let result: HashMap<&str, &str> = [("name", "Luke")].iter().collect();
| ^^^^^^^ a collection of type `std::collections::HashMap<&str, &str>` 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<&str, &str>`
没有.cloned()
的代码试图从对元组的引用的迭代器中生成HashMap
,但HashMap::from_iter()
方法需要拥有元组的迭代器。 .cloned()
调用将引用的迭代器转换为拥有元组的迭代器,可以赋予HashMap::from_iter()
(.collect()
将最终调用的内容)
标准库没有为元组引用的迭代器实现HashMap::from_iter()
的原因是因为HashMap
需要拥有元组来从中获取密钥和值,如果它是不可能的传递对元组的引用。