gpt4 book ai didi

asynchronous - Rust:加入并迭代 future 结果

转载 作者:行者123 更新时间:2023-12-03 11:45:05 25 4
gpt4 key购买 nike

我有一些代码可以遍历对象,并在对结果进行某些处理之前依次对每个对象使用异步方法。我想对其进行更改,以便将异步方法调用在执行之前加入到单个future中。下面的重要位在HolderStruct::add_squares中。我当前的代码如下所示:

use anyhow::Result;

struct AsyncMethodStruct {
value: u64
}

impl AsyncMethodStruct {
fn new(value: u64) -> Self {
AsyncMethodStruct {
value
}
}
async fn get_square(&self) -> Result<u64> {
Ok(self.value * self.value)
}
}

struct HolderStruct {
async_structs: Vec<AsyncMethodStruct>
}

impl HolderStruct {
fn new(async_structs: Vec<AsyncMethodStruct>) -> Self {
HolderStruct {
async_structs
}
}
async fn add_squares(&self) -> Result<u64> {
let mut squares = Vec::with_capacity(self.async_structs.len());
for async_struct in self.async_structs.iter() {
squares.push(async_struct.get_square().await?);
}
let mut sum = 0;
for square in squares.iter() {
sum += square;
}

return Ok(sum);
}
}
我想将 HolderStruct::add_squares更改为以下内容:
use futures::future::join_all;
// [...]
impl HolderStruct {
async fn add_squares(&self) -> Result<u64> {
let mut square_futures = Vec::with_capacity(self.async_structs.len());
for async_struct in self.async_structs.iter() {
square_futures.push(async_struct.get_square());
}
let square_results = join_all(square_futures).await;
let mut sum = 0;
for square_result in square_results.iter() {
sum += square_result?;
}

return Ok(sum);
}
}
但是,编译器使用上面的代码给了我这个错误:
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
--> src/main.rs:46:20
|
46 | sum += square_result?;
| ^^^^^^^^^^^^^^ the `?` operator cannot be applied to type `&std::result::Result<u64, anyhow::Error>`
|
= help: the trait `std::ops::Try` is not implemented for `&std::result::Result<u64, anyhow::Error>`
= note: required by `std::ops::Try::into_result`
如何更改代码以不出现此错误?

最佳答案

for square_result in square_results.iter()
在此处丢失 iter()调用。
for square_result in square_results
您似乎在印象中,必须调用 iter()来遍历集合。实际上,任何实现 IntoIterator的东西都可以在for循环中使用。
Vec<T>上调用 iter()将取消切片( &[T]),并在对vectors元素的引用上产生一个迭代器。 ?运算符尝试从 Result中取出值,但这只有在您拥有 Result而不是仅对其进行引用的情况下才有可能。
但是,如果仅在for语句中使用向量本身,它将对 Vec<T>使用 IntoIterator implementation,这将产生 T类型的项目,而不是 &Tsquare_results.into_iter()做同样的事情,尽管更为冗长。在以函数样式la vector.into_iter().map(|x| x + 1).collect()使用迭代器时,它最有用。

关于asynchronous - Rust:加入并迭代 future 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com