小编Cza*_*ero的帖子

如何满足 f32 的 `Sum<T>` 特征要求?

我有以下我正在尝试实现的特征:

pub trait CentralMoment<Output = f32>
where
    Output: Copy,
{
    fn mean(&self) -> Output;
}

impl<T> CentralMoment for [T] {
    fn mean(&self) -> f32 {
        let sum: f32 = self.iter().sum();
        sum / self.len() as f32
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是线路let sum: f32 = self.iter().sum()。编译器告诉我:

the trait bound `f32: Sum<&T>` is not satisfied
  --> src/lib.rs:45:36
   |
45 |         let sum: f32 = self.iter().sum();
   |                                    ^^^ the trait `Sum<&T>` is not implemented for `f32`
   |
help: consider extending the `where` bound, but …
Run Code Online (Sandbox Code Playgroud)

generics iterator traits rust

3
推荐指数
1
解决办法
655
查看次数

标签 统计

generics ×1

iterator ×1

rust ×1

traits ×1