Asynchronous Rust:加入并迭代期货';结果

Asynchronous Rust:加入并迭代期货';结果,asynchronous,rust,Asynchronous,Rust,我有一些迭代对象的代码,在对结果进行处理之前,对每个对象按顺序使用异步方法。我想更改它,以便在执行之前将异步方法调用合并到一个未来中。下面的重要位位于HolderStruct::add_squares中。我当前的代码如下所示: 使用anyhow::Result; 结构异步方法结构{ 数值:u64 } impl AsyncMethodStruct{ fn新(值:u64)->Self{ AsyncMethodStruct{ 价值 } } 异步fn get_square(&self)->结果{ Ok(

我有一些迭代对象的代码,在对结果进行处理之前,对每个对象按顺序使用异步方法。我想更改它,以便在执行之前将异步方法调用合并到一个未来中。下面的重要位位于
HolderStruct::add_squares
中。我当前的代码如下所示:

使用anyhow::Result;
结构异步方法结构{
数值:u64
}
impl AsyncMethodStruct{
fn新(值:u64)->Self{
AsyncMethodStruct{
价值
}
}
异步fn get_square(&self)->结果{
Ok(self.value*self.value)
}
}
结构持有者结构{
异步结构:Vec
}
impl-HolderStruct{
fn新(异步结构:Vec)->Self{
货主结构{
异步结构
}
}
异步fn添加平方(&self)->结果{
让mut squares=Vec::with_capacity(self.async_structs.len());
对于self.async_structs.iter()中的async_struct{
squares.push(async_struct.get_squares().await?);
}
设mut和=0;
对于正方形中的正方形。iter(){
总和+=平方;
}
返回Ok(总和);
}
}
我想将
HolderStruct::add_squares
更改为如下内容:

use futures::future::join_all;
// [...]
impl-HolderStruct{
异步fn添加平方(&self)->结果{
让mut square\u futures=Vec::带有容量(self.async\u structs.len());
对于self.async_structs.iter()中的async_struct{
square\u futures.push(async\u struct.get\u square());
}
让square\u结果=加入所有(square\u期货)。等待;
设mut和=0;
对于square_结果,使用square_结果。iter(){
总和+=平方_结果?;
}
返回Ok(总和);
}
}
但是,编译器使用上面的命令给了我这个错误:

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`
error[E0277]“?”运算符只能应用于实现“std::ops::Try”的值`
-->src/main.rs:46:20
|
46 |和+=平方|结果?;
|^^^^^^^^^^^^^^^^ `?`运算符不能应用于类型`&std::result::result`
|
=帮助:`&std::result::result`未实现特性`std::ops::Try``
=注意:`std::ops::Try::into_result'所需`
如何将代码更改为不存在此错误?

对于square\u结果,使用square\u结果。iter()
在此处丢失
iter()
调用

用于平方结果的平方结果
您似乎有这样一种印象,调用
iter()
是迭代集合所必需的。实际上,实现的任何东西都可以在for循环中使用

调用
Vec
derefs进行切片(
&[T]
),并生成对向量元素引用的迭代器。
运算符尝试从
结果中提取值,但只有当您拥有
结果而不是仅对其进行引用时,才可能这样做

但是,如果只在for语句中使用向量本身,它将使用for
Vec
,这将生成
T
类型的项,而不是
&T

square\u results.into\u iter()
也做了同样的事情,尽管更详细。它在函数式风格中使用迭代器时非常有用,即la
vector.into_iter().map(|x | x+1).collect()