Rust stabilized try_fold and try_for_each

 — 1 minute read

In Rust 1.27 the iterator combinators try_fold and try_for_each have been stabilized. Both allow to iteratively apply a function to elements of an iterator until it’s either exhausted or the first error is encountered through Option::None or Result::Err. For example this can be used for short-circuiting1:

fn main() {
  let stuff = vec![1, 2, 3, 4];
  let mut iter = stuff.into_iter();

  let res = iter
    .try_for_each(|x| not_3(x));

  println!("Reult: {:?}", res);
  println!("Iterator is not exhausted and still has {} elements", iter.len());

// try_for_each expectd Option<()> or Result<(),_> because of Try<Ok = ()>
fn not_3(x: isize) -> Option<()> {
  if x == 3 { return None };

  1. See this playpen