A Question on Iterating Vectors of New Types

Setup: Say that I have a simple struct, named NewType, with two variables: String and Bool. Using this struct, I've constructed a vector of NewTypes inside of a Vec<>.

Question: I tried to perform NewType.iter().filter(|x| x.String.contains("example")).collect(), but received a compiler error of the form:

error: the trait `core::iter::FromIterator<&NewType>` is not implemented for the type `collections::vec::Vec`

note: a collection of type `collections::vec::Vec` cannot be built from an iterator over elements of type `&NewType`

How might I go about solving this error?

Your iterator is returning references, but you're trying to build a vector of values. Either you need to iterate values, perhaps consuming the source with into_iter() instead of iter(), or you need to clone from the references into new values, e.g. .cloned().collect().

BTW, it helps if you can show your example with a link on https://play.rust-lang.org/ -- use the "Shorten" button once you have something demonstrating the problem.

into_iter() worked perfectly while .cloned().collect() simply gave an error that my type doesn't implement the cloned trait. In any case, it's working now. Thanks, I've been trying to figured this out for much of the day.

If you want to allow cloning, you can add #[derive(Clone)] on your type to implement it automatically.

1 Like