rust 类型为Result&lt;Vec< Type>,Error&gt;的值不能从Vec类型的元素上的迭代器构建< Type>

qmelpv7a  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(143)

我正在尝试处理一段代码,得到了这样的错误:

error[E0277]: a value of type `Result<Vec<tor_llcrypto::pk::curve25519::PublicKey>, AuthorizedClientConfigError>` cannot be built from an iterator over elements of type `Vec<tor_llcrypto::pk::curve25519::PublicKey>`
   --> crates/tor-hsservice/src/svc/publish/descriptor.rs:194:10
    |
194 |         .collect();
    |          ^^^^^^^ value of type `Result<Vec<tor_llcrypto::pk::curve25519::PublicKey>, AuthorizedClientConfigError>` cannot be built from `std::iter::Iterator<Item=Vec<tor_llcrypto::pk::curve25519::PublicKey>>`
    |
    = help: the trait `FromIterator<Vec<tor_llcrypto::pk::curve25519::PublicKey>>` is not implemented for `Result<Vec<tor_llcrypto::pk::curve25519::PublicKey>, AuthorizedClientConfigError>`
    = help: the trait `FromIterator<Result<A, E>>` is implemented for `Result<V, E>`
note: the method call chain might not have had the expected associated types

我的代码如下所示:

let auth_client_keys: Result<Vec<curve25519::PublicKey>, Error> = auth_clients
    .authorized_client
    .iter()
    .flat_map(|client| match client {
        Curve25519Key(key) => Ok(vec![**key]),
        DirectoryOfKeys(dir) => {
            let mut keys = Vec::<curve25519::PublicKey>::new();

            Ok(keys)
        }
    })
    .collect()

我不知道如果我用iter()flat_map()迭代一个循环,我怎么能返回到Result<Vec<curve25519::PublicKey>, AuthorizedClientConfigError>这样的类型。我该如何做,并修复上述错误?
用for循环会更好吗,因为这通常更容易?
我期望它将PublicKey类的Map合并到一个for循环中。相反,我得到了上面的错误。

2skhul33

2skhul331#

问题是你在flat_map调用中混淆了ResultVec,所以它是Result而不是Vec。在平面Map上,物品的类型从Result<Vec<T>, E>Vec<T>,我想你希望它到Result<T, E>
要修复它,您可以在调用中交换向量和结果创建:

.flat_map(|client| match client {
    Curve25519Key(key) => vec![Ok(**key)],
    DirectoryOfKeys(dir) => {
        let mut keys = Vec::<curve25519::PublicKey>::new();
        let key_from_dir = read_key_from_dir();
        keys.push(Ok(key_from_dir));
        keys
    }
})

相关问题