如何为泛型 Vec<T> 的向量实现特征?

How to implement a trait for a vector of generic type Vec<T>?

如何为泛型向量实现以下特征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

您需要对 T 而不是 Vec<T> 进行参数化。然后你还需要约束 T 以便你可以进行减法(使用 Sub 特性)并且可以将值复制到内存中(使用 Copy 特性)。数字类型将主要实现这些特征。

use std::ops::Sub;

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

impl<T> Difference<T> for Vec<T>
where
    T: Sub<Output = T> + Copy,
{
    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());
}