I'm implementing a collection type that holds a vector of structs. I want to implements a bunch of methods to sort my vector in various ways. It is important that each function returns a collection of values because the call-site will modify the results further, which may imply deleting or changing values and none of these changes should propagate back to the original collection.
The struct is very basic:
#[derive(PartialEq, Debug, Clone)]
pub struct Shoe {
size: u32,
style: String,
}
The collection type just wraps the struct into a vector, like so:
#[derive(Debug, PartialEq, Clone)]
pub struct ShoesInventory {
shoes: Vec<Shoe>
}
I want to filter all existing shoes according to given size, and return the result as a separate vector. Basically, iterate, filter, and collect. However, when I write this,
impl ShoesInventory {
pub fn new(shoes: Vec<Shoe>) -> ShoesInventory {
ShoesInventory { shoes }
}
pub fn shoes_in_size(&self, shoe_size: u32) -> Vec<Shoe> {
self.shoes.iter().filter(| s| s.size == shoe_size).collect()
}
}
I'm getting the following compiler error
error[E0277]: a value of type `Vec<Shoe>` cannot be built from an iterator over elements of type `&Shoe`
--> src/shoes.rs:18:9
|
18 | self.shoes.iter().filter(| s| s.size == shoe_size).collect()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ------- required by a bound introduced by this call
| |
| value of type `Vec<Shoe>` cannot be built from `std::iter::Iterator<Item=&Shoe>`
|
= help: the trait `FromIterator<&Shoe>` is not implemented for `Vec<Shoe>`
If I try to clone the element in the closure, it doesn't fix anything and I still get the same error. It's not so clear what the problem is b/c on another vector this code pattern actually works. For example, when you use another vector with a primitive type, say integer, the iterator, map/filter, collect pattern just works fine.
let v1: Vec<i32> = vec![1, 2, 3];
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); // no problem here
However, when the vector element contains a struct or a string, things get hairy.
I understand the error basically says, that the FromIterator is not implemented, but why? And how do I fix this?