小编nov*_*ean的帖子

如何将一系列 Result<(A, B), E> 解压缩到 (Vec<A>, Vec<B>) 并在第一个错误时停止?

我想做这样的事情:

enum MyEnum {
    Foo(Vec<Stuff>),
    // ...
}

impl MyEnum {
    fn do_sth(&self) -> Result<Bar, E> {
        match *self {
            MyEnum::Foo(ref vec) => {
                let (a, b): (Vec<A>, Vec<B>) = vec
                    .iter()
                    .map(|thing| thing.make_a_tuple(arg)) // returns Result<(A, B), E>
                    .collect::<Result<_, _>>()? // stop on first error
                    .unzip();

                // use a and b
            }

            // other cases
        }

        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这无法与error: the type of this value must be known in this context. 通过反复试验,我让它像这样编译

    fn do_sth(&self) -> Result<Bar, …
Run Code Online (Sandbox Code Playgroud)

iterator rust

5
推荐指数
1
解决办法
246
查看次数

标签 统计

iterator ×1

rust ×1