如何为通用类型Vec<T>的向量实现以下特征?

例如,如何以通用方式实现以下(有效的)Difference特征(例如使其对Vec<i32>Vec<f32>Vec<f64>有效)?

trait Difference {
    fn diff(&self) -> Vec<f64>;
}

impl Difference for Vec<f64> {
    fn diff(&self) -> Vec<f64> {
        self.windows(2)
            .map(|slice| (slice[0] - slice[1]))
            .collect()
    }
}

fn main() {
    let vector = vec![1.025_f64, 1.028, 1.03, 1.05, 1.051];
    println!("{:?}", vector.diff());
}

at the documentation看,似乎应该是这样的:
trait Difference<Vec<T>> {
    fn diff(&self) -> Vec<T>;
}

impl Difference for Vec<T> {
    fn diff(&self) -> Vec<T> {
        self.windows(2)
            .map(|slice| (slice[0] - slice[1]))
            .collect()
    }
}

fn main() {
    let vector = vec![1.025_f64, 1.028, 1.03, 1.05, 1.051];
    println!("{:?}", vector.diff());
}

但是,以上结果导致:

error: expected one of `,`, `:`, `=`, or `>`, found `<`
 --> src/main.rs:2:21
  |
2 | trait Difference<Vec<T>> {
  |                     ^ expected one of `,`, `:`, `=`, or `>` here

我尝试了其他几种变体,但是所有这些变体都会导致更长的错误消息。

最佳答案

正确的语法是:

trait Difference<T> { /* ... */ }

impl<T> Difference<T> for Vec<T> { /* ... */ }

然后,您将需要T实现减法:

error[E0369]: binary operation `-` cannot be applied to type `T`
 --> src/main.rs:9:26
  |
9 |             .map(|slice| (slice[0] - slice[1]))
  |                          ^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `T` might need a bound for `std::ops::Sub`

并且您可以复制值:

error[E0508]: cannot move out of type `[T]`, a non-copy slice
  --> src/main.rs:10:27
   |
10 |             .map(|slice| (slice[0] - slice[1]))
   |                           ^^^^^^^^ cannot move out of here
impl<T> Difference<T> for Vec<T>
where
    T: std::ops::Sub<Output = T> + Copy,
{
    // ...
}

或者可以减去对T的引用:
impl<T> Difference<T> for Vec<T>
where
    for<'a> &'a T: std::ops::Sub<Output = T>,
{
    fn diff(&self) -> Vec<T> {
        self.windows(2)
            .map(|slice| &slice[0] - &slice[1])
            .collect()
    }
}

也可以看看:
  • How to implement non-generic trait on a struct with a generic parameter
  • Using a generic in a struct and implementing via a trait
  • Requiring implementation of Mul in generic function
  • How does for<> syntax differ from a regular lifetime bound?
  • 关于generics - 如何为通用类型Vec <T>的矢量实现特征?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50381524/

    10-10 18:34