实现泛型类型的均值函数
我正在尝试编写一个函数以返回Vector
的均值.我希望它可以与泛型类型一起使用,但是在实现它时遇到了一些困难.
I'm trying to write a function to return the mean of a Vector
. I want it to work with generic types but I'm having some difficulty implementing it.
extern crate num; // 0.2.0
use num::Zero;
use std::ops::{Add, Div};
pub struct Vector<T> {
pub size: usize,
pub data: Vec<T>,
}
impl<T: Copy + Zero + Add<T, Output = T>> Vector<T> {
pub fn sum(&self) -> T {
self.data.iter().fold(T::zero(), |sum, &val| sum + val)
}
}
impl<T: Copy + Zero + Add<T, Output = T> + Div<T, Output = T>> Vector<T> {
pub fn mean(&self) -> T {
let sum = self.sum();
sum / self.data.len()
}
}
游乐场.
上面的示例未编译,因为self.data.len()
是usize
,而sum
是T
类型:
The above example doesn't compile as self.data.len()
is a usize
and sum
is of type T
:
error[E0308]: mismatched types
--> src/lib.rs:20:15
|
20 | sum / self.data.len()
| ^^^^^^^^^^^^^^^ expected type parameter, found usize
|
= note: expected type `T`
found type `usize`
我知道我可以将签名更改为:
I know I could change the signature to:
impl<T: Copy + Zero + Add<T, Output = T> + Div<usize, Output = T>> Vector<T>
它将编译-但这并未为Rust原语类型实现.我该怎么办?
It would compile - but this isn't implemented for the Rust primitive types. How should I go about this?
原始类型实现特征 "rel =" nofollow noreferrer> num
板条箱,以允许在原始类型(包括usize
)之间进行转换.我们可以在函数上添加FromPrimitive
绑定,然后将usize
转换为T
:
The primitive types implement the FromPrimitive
trait, defined in the num
crate, to allow conversions between primitive types, including usize
. We can add a FromPrimitive
bound on the function, and then we can convert the usize
to a T
:
extern crate num; // 0.2.0
use num::{FromPrimitive, Zero};
use std::ops::{Add, Div};
impl<T> Vector<T>
where
T: Copy + Zero + Add<T, Output = T> + Div<T, Output = T> + FromPrimitive,
{
pub fn mean(&self) -> T {
let sum = self.sum();
sum / FromPrimitive::from_usize(self.data.len()).unwrap()
}
}