[英]How can I implement a default implementation of a generic trait for some generic type?
我想在一些泛型类型Vec<T>
上实现特征MovingAverage
的默认实现,但我显然做错了,因为我可以使它适用于具体类型Vec<f64>
但不适用于具体类型Vec<i32>
. 这是错误中的 output :
error[E0599]: the method `sma` exists for struct `Vec<{integer}>`, but its trait bounds were not satisfied
--> src/main.rs:8:22
|
8 | let smai = numsi.sma(n);
| ^^^ method cannot be called on `Vec<{integer}>` due to unsatisfied trait bounds
|
::: /home/czar/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:397:1
|
397 | pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
| ------------------------------------------------------------------------------------------------ doesn't satisfy `Vec<{integer}>: MovingAverage`
|
= note: the following trait bounds were not satisfied:
`f64: AddAssign<{integer}>`
which is required by `Vec<{integer}>: MovingAverage`
`f64: SubAssign<{integer}>`
which is required by `Vec<{integer}>: MovingAverage`
这是我来自 mar.rs 的代码:
pub trait MovingAverage<Output = Vec<f64>> {
fn sma(&self, periods: usize) -> Output;
}
impl<T> MovingAverage for Vec<T>
where
T: Copy + Num,
f64: AddAssign<T> + SubAssign<T>,
{
fn sma(&self, periods: usize) -> Vec<f64> {
let mut sum = 0f64;
let mut ma = Vec::<f64>::new();
for i in 0..self.len() {
if i >= periods {
ma.push(sum / periods as f64);
sum -= self[i - periods];
}
sum += self[i];
}
ma
}
}
我的 main.rs
let numsf = vec![5., 10., 3., 9., 8., 7.];
let mut numsi = vec![2, 4, 3, 5, 1, 1];
let n = 2;
let smaf = numsf.sma(n);
let smai = numsi.sma(n); // doesnt work here
我的错误发生了什么,go 关于在泛型类型上实现特征而不必为每个具体类型实现特征的正确方法是什么? 提前致谢,如果您需要任何进一步的说明,请告诉我。
也许更好的界限是T: Into<f64>
。 然后,您可以在访问每个元素时简单地将其转换为f64
。 此外,如果您为[T]
而不是Vec<T>
实现特征,它也适用于切片。 尝试这个:
impl<T: Copy + Into<f64>> MovingAverage for [T] {
fn sma(&self, periods: usize) -> Vec<f64> {
let mut sum = 0f64;
let mut ma = Vec::<f64>::new();
for i in 0..self.len() {
if i >= periods {
ma.push(sum / periods as f64);
sum -= self[i - periods].into();
}
sum += self[i].into();
}
ma
}
}
(旁注:我认为您的代码可能会无意中忽略输入的最后一个元素)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.