将& T的迭代器收集到T的集合中的惯用方式是什么? [英] What is an idiomatic way to collect an iterator of &T into a collection of Ts?
本文介绍了将& T的迭代器收集到T的集合中的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将遍历&str
的切片上的迭代器收集到&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>>();
}
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>>();
}
推荐答案
如果T
实现了Copy
,则可以使用 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屋!
查看全文