• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


30 Nov, 2024

Updated at 05 Dec, 2024

How to create iterator with results

Hi everyone,

I'm trying to create an iterator that returns Result<Vec<Result<Something>>> each time. The first Result is related to the iterator creation, while the vector is the iterator itself (simplified for the question). Each item in the iterator should return a Result, allowing some iterations to yield errors, but the user should be able to ignore them.

My current function looks like this:

fn get_segments() -> Result<impl Iterator<Item = Result<Segment>> + '_> {
    let mut some_bool = false;
    call_something()?; 
    Ok(std::iter::from_fn(move || {
        for ... {
            for ... {
                call_something()?; // I can't bubble up errors like this
                if condition {
                    some_bool = true; // state is not preserved across calls
                }
                return Some(Ok(Segment { ... })); // it yields once, but I expect multiple yields
            }
        }
        None // No more items to yield
    }))
}

The problem is that the iterator yields only once (once it returns, it doesn't yield more). Also, I'm finding it difficult to properly bubble up errors.

This is the actual code I'm working on: pyannote-rs/segment.rs#L27

Any help would be appreciated! Thanks!

1 post - 1 participant

Read full topic