banner
davirain

davirain

twitter
github
知乎
twitter

將 Vec<Result<T>, E> 轉換為 Result<Vec<T>, E>

將 Vec<Result<T, E>> 轉換為 Result<Vec, E>,您可以使用 Iterator trait 中的 try_fold () 方法。以下是一個示例實現:

在這裡,我們使用 into_iter () 將 Vec 轉換為迭代器。然後我們調用 try_fold (),傳入 Vec::new () 作為初始值,以及一個接受兩個參數(累加器 acc 和 Result res)的閉包。

fn vec_result_to_result_vec<T, E>(v: Vec<Result<T, E>>) -> Result<Vec<T>, E> {
    v.into_iter().try_fold(Vec::new(), |mut acc, res| {
        match res {
            Ok(t) => {
                acc.push(t);
                Ok(acc)
            },
            Err(e) => Err(e)
        }
    })
}

閉包模式匹配 Result 變體,將 Ok 值推入 acc 向量並返回 Ok (acc),如果 Result 是 Err,則返回 Err (e)。try_fold () 方法將繼續迭代迭代器中的剩餘項目,將更新後的累加器值傳遞給每個後續閉包調用。

如果原始 Vec 中的任何一個 Result 是 Err,try_fold () 將中斷並返回遇到的第一個 Err。否則,它將返回帶有解封的 T 值的 Vec 的 Ok (acc)。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。