将 &T 的迭代器收集到 T 集合中的惯用方法是什么? [英] What is an idiomatic way to collect an iterator of &T into a collection of Ts?
问题描述
我需要将 &str
s 切片上的迭代器收集到 &str
s 集合中.问题是迭代器产生 &&str
s.
I need to collect an iterator over a slice of &str
s into a collection of &str
s. The problem is that the iterator yields &&str
s.
我尝试从 &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
实现了 Clone
和 Copy
,因此您可以使用 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();
这篇关于将 &T 的迭代器收集到 T 集合中的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!