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.
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.
The problem:
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>`
My solution:
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…