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

时间:2018-05-16 23:58:45

标签: generics syntax rust traits

如何为通用类型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

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

2 个答案:

答案 0 :(得分:4)

正确的语法是:

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()
    }
}

另见:

答案 1 :(得分:2)

您需要对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());
}
相关问题