如何从外部箱子中实现为其他特征添加特征

时间:2019-02-08 21:38:30

标签: generics rust

我正在尝试实现Vector结构。声明如下:

use num_traits::Float;

pub struct Vec3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T> Vec3<T>
where
    T: Float,
{
    pub fn new(x: T, y: T, z: T) -> Vec3<T> {
        Vec3 { x, y, z }
    }
}

我希望能够将此结构的实例添加到通用浮点值。我认为就我而言,我将成为实现Float特性的任何人:

let vec = Vec3::new(1.0, 1.0, 1.0);
let res = 1.0 + vec; // this should work for both f32 and f64

我本来只是为Add实现Float特性,所以我写道:

use std::ops::Add;

impl<T: Float> Add<Vec3<T>> for T {
    type Output = Vec3<T>;

    fn add(self, other: Vec3<T>) -> Vec3<T> {
        Vec3::new(self + other.x, self + other.y, self + other.z)
    }
}

这给了我以下错误:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
  --> src/lib.rs:20:1
   |
20 | impl<T: Float> Add<Vec3<T>> for T {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
   |
   = note: only traits defined in the current crate can be implemented for a type parameter

我在网上可以找到的最接近的相关解决方案与错误消息所建议的相同:用结构体包装Float特性,这不符合我的要求。我还试图声明一个包含Float的局部特征,但这并没有真正的帮助。

0 个答案:

没有答案