【问题标题】:What is an idiomatic way to collect an iterator of &T into a collection of Ts?将 &T 的迭代器收集到 T 集合中的惯用方法是什么?
【发布时间】:2019-12-26 20:32:45
【问题描述】:

我需要将&strs 切片上的迭代器收集到&strs 的集合中。问题是迭代器产生&&strs。

我尝试从&word 映射到word,虽然它有效,但我不知道它是否被认为是好的,或者是否有更好的选择。

问题:

use std::collections::HashSet;

fn main() {
    let words = &["hello", "world", "I'm", "a", "Rustacean!"];
    let hashset = words.iter().collect::<HashSet<&str>>();
}

Playground

error[E0277]: a collection of type `std::collections::HashSet<&str>` cannot be built from an iterator over elements of type `&&str`
 --> src/main.rs:5:32
  |
5 |     let hashset = words.iter().collect::<HashSet<&str>>();
  |                                ^^^^^^^ a collection of type `std::collections::HashSet<&str>` cannot be built from `std::iter::Iterator<Item=&&str>`
  |
  = help: the trait `std::iter::FromIterator<&&str>` is not implemented for `std::collections::HashSet<&str>`

我的解决方案:

use std::collections::HashSet;

fn main() {
    let words = &["hello", "world", "I'm", "a", "Rustacean!"];
    let hashset = words.iter().map(|&w| w).collect::<HashSet<&str>>();
}

Playground

【问题讨论】:

    标签: reference rust iterator


    【解决方案1】:

    骑自行车是从一个城市到另一个城市的惯用方式吗?就像软件(和生活)中的大多数事情一样,它取决于。

    如果你的类型实现了Copy

    我更喜欢这些顺序:

    1. some_iter.copied()
    2. some_iter.cloned()
    3. some_iter.map(|&amp;v| v)
    4. some_iter.map(|v| *v)
    5. some_iter.map(Clone::clone)
    6. some_iter.map(|v| v.clone())

    如果你的类型实现了Clone

    我更喜欢这些顺序:

    1. some_iter.cloned()
    2. some_iter.map(Clone::clone)
    3. some_iter.map(|v| v.clone())

    如果您的类型没有实现 Copy 或 Clone

    那么你不能轻易地创造一个拥有的价值。该类型可能实现了ToOwned,或者您可以在map 内部调用定制的函数或方法,或者您可能根本无法执行任何操作。


    在你的情况下,我会使用words.iter().copied().collect::&lt;HashSet&lt;_&gt;&gt;()。

    另见:

    【讨论】:

      【解决方案2】:

      如果T 实现Copy,那么您可以使用Iterator::copied。否则,如果它实现了Clone,那么你可以使用Iterator::cloned。像任何不可变引用一样,&amp;str 实现了Clone 和Copy,因此您可以使用copied:

      let hashset: HashSet<&str> = words.iter().copied().collect();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-27
        • 2013-10-26
        • 2011-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多