When should I use `drain` vs `into_iter`?

They are somewhat redundant with each other. However, as you say, Drain just borrows the vector, in particular, it has a lifetime connected with the vector. If one is wishing to return an iterator, or otherwise munge iterators in the most flexible way possible, using into_iter is better, since it’s not chained to the owner … Read more

Type issue with Iterator collect

The type &(&str, &str) comes from what iter() on a Vec returns: fn iter(&self) -> Iter<T> where Iter<T> implements Iterator<Item=&T>: impl<‘a, T> Iterator for Iter<‘a, T> { type Item = &’a T … } In other words, iter() on a vector returns an iterator yielding references into the vector. cloned() solves the problem because it … Read more

Is there a trait supplying `iter()`?

No, there is no trait that provides iter(). However, IntoIterator is implemented on references to some containers. For example, Vec<T>, &Vec<T> and &mut Vec<T> are three separate types that implement IntoIterator, and you’ll notice that they all map to different iterators. In fact, Vec::iter() and Vec::iter_mut() are just convenience methods equivalent to &Vec::into_iter() and &mut … Read more

In Rust, is a vector an Iterator?

No, a vector is not an iterator. But it implements the trait IntoIterator, which the for loop uses to convert the vector into the required iterator. In the documentation for Vec you can see that IntoIterator is implemented in three ways: for Vec<T>, which is moved and the iterator returns items of type T, for … Read more

How can I add new methods to Iterator?

In your particular case, it’s because you have implemented your trait for an iterator of String, but your vector is providing an iterator of &str. Here’s a more generic version: use std::collections::HashSet; use std::hash::Hash; struct Unique<I> where I: Iterator, { seen: HashSet<I::Item>, underlying: I, } impl<I> Iterator for Unique<I> where I: Iterator, I::Item: Hash + … Read more

tech