gpt4 book ai didi

rust - 调用iter()。sum(): the trait bound `f64: std::iter::Sum<&std::vec::Vec>` is not satisfied时出错

转载 作者:行者123 更新时间:2023-12-03 11:41:57 26 4
gpt4 key购买 nike

我正在为应该返回f64Error的函数而苦苦挣扎。我尝试了许多组合,但没有成功。

fn_rayon_parallel(&self) -> Result<f64, Box<dyn Error + Send + Sync>>  {

let all_payoffs = (0..10000).into_par_iter().map(
|_| { //things could go very wrong here
match self.get_one_payoff() {
Ok(payoff) => {Ok(payoff)},
Err(e) => Err(e)
}
}
).collect::<Result<Vec<_>, _>>();

//this is the part I am struggling with, does not compile
//I need to return either f64 or Error

match all_payoffs {
Ok(_v) => Ok(2.34 * (1.0/10000.0) * (all_payoffs.iter().sum::<f64>())),
Err(e) => Err(From::from("There was an error in calculating Discounted Payoffs."))
}


}

错误:
error[E0277]: the trait bound `f64: std::iter::Sum<&std::vec::Vec<f64>>` is not satisfied
--> src/main.rs:81:69
|
81 | Ok(_v) => Ok(2.34 * (1.0/10000.0) * (all_payoffs.iter().sum::<f64>())),
| ^^^ the trait `std::iter::Sum<&std::vec::Vec<f64>>` is not implemented for `f64`
|
= help: the following implementations were found:
<f64 as std::iter::Sum<&'a f64>>
<f64 as std::iter::Sum>

Playground

最佳答案

您的主要问题就在这里(简化了一下):

match all_payoffs {
Ok(_v) => Ok(1.0 * (all_payoffs.iter().sum::<f64>())),
Err(e) => { /*...*/ }
}
请注意,您的 all_payoffs变量的类型为 Result<Vec<f64>, Box<dyn Error + Send>>。因此,当您执行 .iter()时,您会认为您正在获得类型为 &f64的向量值的迭代器,但实际上是获得了 Resultiterator for the ok-value!
这在很多情况下都很方便,例如,如果使用 Iterator::flatten(),则可以使用 Ok()对所有值求和,如果使用 0.0,则可以返回 Err():
let x = all_payoffs.iter().flatten().sum::<f64>();
但是在这里,编译器认为您正在尝试对向量求和,而这是无法完成的,因此会出现错误消息:

the trait bound f64: std::iter::Sum<&std::vec::Vec<f64>> is not satisfied


这基本上意味着:您不能求和一堆 &Vec<f64>并得到一个 f64
解决方案就在那里,可以使用 _v:
Ok(v) => Ok(1.0 * v.iter().sum::<f64>()),
现在就可以了!

关于rust - 调用iter()。sum(): the trait bound `f64: std::iter::Sum<&std::vec::Vec<f64>>` is not satisfied时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61803480/

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