【发布时间】: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>>();
}
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>>();
}
【问题讨论】: