Generics 锈干性状和仿制药-impl Add和Mul几乎相同
我有下面的玩具代码,它使用泛型来实现3d向量上的一些操作,作为3个泛型元素的结构Generics 锈干性状和仿制药-impl Add和Mul几乎相同,generics,rust,traits,generic-programming,Generics,Rust,Traits,Generic Programming,我有下面的玩具代码,它使用泛型来实现3d向量上的一些操作,作为3个泛型元素的结构 use std::ops::Add; use std::ops::Mul; #[derive(Debug)] pub struct Vec3<T> { x: T, y: T, z: T, } impl<T> Vec3<T> { pub fn new(x: T, y: T, z: T) -> Vec3<T> {
use std::ops::Add;
use std::ops::Mul;
#[derive(Debug)]
pub struct Vec3<T> {
x: T,
y: T,
z: T,
}
impl<T> Vec3<T> {
pub fn new(x: T, y: T, z: T) -> Vec3<T> {
Vec3 { x, y, z }
}
}
impl<T: Add<Output = T> + Copy> Add<T> for &Vec3<T> {
type Output = Vec3<T>;
fn add(self, other: T) -> Vec3<T> {
Vec3 {
x: self.x + other,
y: self.y + other,
z: self.z + other,
}
}
}
impl<T: Add<Output = T> + Copy> Add<&Vec3<T>> for &Vec3<T> {
type Output = Vec3<T>;
fn add(self, other: &Vec3<T>) -> Vec3<T> {
Vec3 {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl<T: Mul<Output = T> + Copy> Mul<T> for &Vec3<T> {
type Output = Vec3<T>;
fn mul(self, other: T) -> Vec3<T> {
Vec3 {
x: self.x * other,
y: self.y * other,
z: self.z * other,
}
}
}
impl<T: Mul<Output = T> + Copy> Mul<&Vec3<T>> for &Vec3<T> {
type Output = Vec3<T>;
fn mul(self, other: &Vec3<T>) -> Vec3<T> {
Vec3 {
x: self.x * other.x,
y: self.y * other.y,
z: self.z * other.z,
}
}
}
关于你的问题,关于将创建Add、Mul等impl的二进制操作的一个更一般的特征。就我所知,没有,我认为你不能,因为孤儿规则。你可以:
- 为二进制操作特性编写一个
- 使用现有的Vector3,比如已经为您实现这些特性的
- 尝试泛化以处理具有多个成员的结构
trait Op<T>:Add<T>+Mul<T>{
fn op(&self)->T;
}