将 &T 的迭代器收集到 T 集合中的惯用方法是什么? [英] What is an idiomatic way to collect an iterator of &T into a collection of Ts?

查看:13
本文介绍了将 &T 的迭代器收集到 T 集合中的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to collect an iterator over a slice of &strs into a collection of &strs. The problem is that the iterator yields &&strs.

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

I tried to map from &word to word, and while it works, I don't know if it is considered good or if there are better options available.

问题:

use std::collections::HashSet;

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

游乐场p>

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>>();
}

游乐场p>

推荐答案

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

If T implements Copy then you can use Iterator::copied. Otherwise, if it implements Clone then you can use Iterator::cloned. Like any immutable reference, &str implements both Clone and Copy, so you can use copied:

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

这篇关于将 &amp;T 的迭代器收集到 T 集合中的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆