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
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();
Is a bicycle an idiomatic way to get from one city to another? Like most things in software (and life), it depends.
Copy
I'd prefer these in this order:
some_iter.copied()
some_iter.cloned()
some_iter.map(|&v| v)
some_iter.map(|v| *v)
some_iter.map(Clone::clone)
some_iter.map(|v| v.clone())
Clone
I'd prefer these in this order:
some_iter.cloned()
some_iter.map(Clone::clone)
some_iter.map(|v| v.clone())
Copy
or Clone
Then you cannot trivially create an owned value. The type may implement ToOwned or there may be a bespoke function or method that you can call inside of map
, or you may simply not be able to do anything.
In your case, I'd use words.iter().copied().collect::<HashSet<_>>()
.
See also: