What is an idiomatic way to collect an iterator of &T into a collection of Ts?

Is a bicycle an idiomatic way to get from one city to another? Like most things in software (and life), it depends.

If your type implements Copy

I’d prefer these in this order:

  1. some_iter.copied()
  2. some_iter.cloned()
  3. some_iter.map(|&v| v)
  4. some_iter.map(|v| *v)
  5. some_iter.map(Clone::clone)
  6. some_iter.map(|v| v.clone())

If your type implements Clone

I’d prefer these in this order:

  1. some_iter.cloned()
  2. some_iter.map(Clone::clone)
  3. some_iter.map(|v| v.clone())

If your type doesn’t implement 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:

Leave a Comment