implementin filter for vector of custom struct in RUST

21 views Asked by At

i am new to rust, like started yesterday new, and i am creating a todo/calendar app to learn. i am the very initial stage of defining by structures and implementations. i am stuck at creating a function that filters the vector. But i am getting an error while using filter() and collect() . i am not sure what needs to be done tbh , i did go on to learn more about serialization but couldnt get far. I would appreciate some advice or explanation what is the issue coz i dont get it.

the error is


error[E0277]: a value of type `TodoList<'_>` cannot be built from an iterator over elements of type `structs::Todoitem::Todoitem<'_>`
    --> src/structs/Todolist.rs:92:26
     |
92   |             .into_iter().collect()
     |                          ^^^^^^^ value of type `TodoList<'_>` cannot be built from `std::iter::Iterator<Item=structs::Todoitem::Todoitem<'_>>`

my implementations and structs are as follows.

pub struct TodoList<'a> {
    pub items: Vec<Todoitem<'a>>,
}

... //my implementation for filter is..
    fn helperFilterStatus(&mut self, target: Types::Status) -> TodoList<'a> {
        self.items
            .into_iter().filter(|x_item| x_item.status==target).collect()
    }

and lastly todoitem

pub struct Todoitem<'a> {
    pub id: u32,
    pub title: &'a str,
    ...
  }

i have not added my full implementation but i can share git link if required.

1

There are 1 answers

1
shiv On

Comment on reddit helped: https://www.reddit.com/r/rust/comments/1bn27hy/implementing_filter_for_vector_of_custom_struct/

impl<'a>  FromIterator<Todoitem<'a>> for TodoList<'a>  {
    fn from_iter<T: IntoIterator<Item = Todoitem<'a>> >  (iter: T) -> Self {
        let mut c =  TodoList { items: Vec::new() };
        for i in iter {
            c.add_item(i)
        }
        c
    }
}
    fn helperFilterStatus(&mut self, target: Types::Status) ->TodoList<'a>{
         self.items
            .drain(..).filter(|x_item| x_item.status==target).collect()
    }