I'm not new to programming by any means but am pretty new to Rust. I really like certain things about the language, but it seems whenever I try to do something slightly more advanced I run into issues. I'm finding that I do not yet know how to read the rust error messages and docs like I can in (i.e. C++ or Typescript).
I was hoping to assert my own understanding of how to use the language by implementing a filter_none
on iterables that contain options.
To start off--I decided to see if I can do what I want to begin with:
fn filter_none<'a, T>(item: &'a &Option<T>) -> bool {
match item {
None => false,
Some(_) => true,
}
}
fn main() {
let vec: Vec<Option<i32>> = vec![None, Some(1), Some(2), None, Some(3)];
let filtered_vec: Vec<&Option<i32>> = vec
.iter()
.filter(filter_none)
.collect();
println!("{:?}", filtered_vec);
}
This works. Now to implement this as a trait on iterables I attempted to add the following code:
use std::slice::Iter;
use std::iter::Filter;
fn filter_none<'a, T>(item: &'a &Option<T>) -> bool {
match item {
None => false,
Some(_) => true,
}
}
trait FilterNone<T> {
// Have it seamlessly return a filter object
fn filter_none<P>(self) -> Filter<Self, P>
where
Self: Iterator<Item = Option<T>> + Sized,
P: FnMut(&Option<T>) -> bool,
{
// apply filter_none as a filter and return
self.filter(filter_none::<'a, T>)
}
}
// Implement FilterNone on all iterables of Option<T>
// pass along lifetime for filter_none
impl<'a, T> FilterNone<T> for Iter<'a, Option<T>> {}
fn main() {
let vec: Vec<Option<i32>> = vec![None, Some(1), Some(2), None, Some(3)];
let filtered_vec: Vec<&Option<i32>> = vec
.iter()
.filter_none()
.collect();
println!("{:?}", filtered_vec);
}
After many iterations I seem to be unable to properly match the type of the Filter callable with either a static function or a closure. I imagine it might have something to do with a missing lifetime but I'm clearly missing something.
It would be very helpful for me if someone could help explain what's missing to accomplish what I'm trying to do and why. Thank you.