Generics 如何为外部板条箱中的另一个特性实现添加特性

Generics 如何为外部板条箱中的另一个特性实现添加特性,generics,rust,Generics,Rust,我正在尝试实现一个向量结构。声明如下: 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 }

我正在尝试实现一个
向量
结构。声明如下:

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
实现
Add
特性,所以我写了:

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)
    }
}
使用std::ops::Add;
对T的impl-Add{
类型输出=Vec3;
fn添加(自身,其他:Vec3)->Vec3{
Vec3::new(self+other.x、self+other.y、self+other.z)
}
}
这给了我以下错误:

error[E0210]:类型参数'T'必须用作某些本地类型(例如'MyStruct')的类型参数
-->src/lib.rs:20:1
|
20 | T的简单添加{
|必须将类型参数“T”用作某些本地类型的类型参数
|
=注意:类型参数只能实现当前板条箱中定义的特征

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

为什么不在定义Vec3的地方实现插件板条箱呢?因为正如你所发现的,现在有办法在rust中做这样的事情。@ali zeinali我就是这么做的。我不是很确定,但我认为问题是我在这种情况下使用了
Float
trait是错误的。让res=vec+1.0解决你的问题吗?@AliZeinali我得到了这个实现,但我希望它能以两种方式工作。谢谢l顺便说一句,我看一下,似乎不可能使用
let res=1.0+vec
,因为您必须为
Float
实现
trait,而在rust中是不允许的
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)
    }
}