this post was submitted on 17 Jan 2022
11 points (92.3% liked)

Rust Programming

8074 readers
1 users here now

founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[โ€“] asonix@lemmy.ml 1 points 2 years ago* (last edited 2 years ago) (1 children)

i might try

let res = collection.into_iter().map(|item| item.fallible_operation()).fold(Ok(Vec::new()), |acc, res| {
    match (acc, res) {
        (Ok(mut vec), Ok(item)) => {
            vec.push(item);
            Ok(vec)
        (Err(mut vec), Err(error)) => {
            vec.push(error);
            Err(vec)
        }
        (Ok(_), Err(error)) => Err(vec![error]),
        _ => acc,
    }
});

Maybe expand it with

pub trait Evert<T, E> {
    fn evert(self) -> Result<Vec<T>, Vec<E>>;
}

impl<I, T, E> Evert<T, E> for I
where
    I: IntoIterator<Item = Result<T, E>>,
{
    fn evert(self) -> Result<Vec<T>, Vec<E>> {
        self.into_iter().fold(/* implementation from above */)
    }
}

fn main() {
    let result = vec![Ok(1), Err(3), Ok(4), Err(8)].evert();
    assert_eq!(result, Err(vec![3, 8]));
}