Good Way to Handle a Result Inside of a Closure

I want to specify a filter for an iterator, but part of the filter closure requires calling a function that returns a Result, which means that I have to have a way to handle the Result in the filter. Normally I would just use the ? operator to propagate the error, but because the filter is inside of a closure, I can’t return a Result, I have to return a bool. Is there any way to have the closure propagate the error from inside of the closure to the function that it is in?

No, but you can collect into a Result or use filter_map.

let x : Result<Vec<_>, _> = iter.collect();
iter.filter_map(|x| filter_function(x).ok());
1 Like

Awesome, that will be perfect. Thanks!