为什么标准库实现不会在没有克隆()的元组阵列迭代器上收集?

时间:2017-12-14 14:56:26

标签: rust

此代码有效:

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>`

我的理解是标准库为元组实现了很多东西,但不是这种情况?为什么不编译呢?

1 个答案:

答案 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需要拥有元组来从中获取密钥和值,如果它是不可能的传递对元组的引用。