gpt4 book ai didi

rust - 为自定义特征提供一揽子特征实现

转载 作者:行者123 更新时间:2023-11-29 07:52:30 25 4
gpt4 key购买 nike

我正在实现一个用于练习的快速几何 crate ,我想实现两个结构,VectorNormal(这是因为标准向量和法线向量映射通过某些变换不同)。我已经实现了以下特征:

trait Components {
fn new(x: f32, y: f32, z: f32) -> Self;
fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;
}

我还想将两个向量和两个法线相加,所以我的 block 看起来像这样:

impl Add<Vector> for Vector {
type Output = Vector;
fn add(self, rhs: Vector) -> Vector {
Vector { vals: [
self.x() + rhs.x(),
self.y() + rhs.y(),
self.z() + rhs.z()] }
}
}

Normalimpl 几乎完全相同。我真正想要的是为每个实现 Components 的结构提供一个默认的 Add impl,因为通常,它们都会以相同的方式添加(例如,第三个结构称为 Point 会做同样的事情)。除了为 PointVectorNormal 编写三个相同的实现之外,还有其他方法可以做到这一点吗?可能看起来像这样的东西:

impl Add<Components> for Components {
type Output = Components;
fn add(self, rhs: Components) -> Components {
Components::new(
self.x() + rhs.x(),
self.y() + rhs.y(),
self.z() + rhs.z())
}
}

其中“Components”会自动被适当的类型替换。我想我可以在宏中完成,但对我来说这似乎有点老套。

最佳答案

在 Rust 中,可以定义泛型 impl s,但是一致性规则有一些重要的限制。你想要一个 impl是这样的:

impl<T: Components> Add<T> for T {
type Output = T;
fn add(self, rhs: T) -> T {
T::new(
self.x() + rhs.x(),
self.y() + rhs.y(),
self.z() + rhs.z())
}
}

不幸的是,这不会编译:

error: type parameter T must be used as the type parameter for some local type (e.g. MyStruct<T>); only traits defined in the current crate can be implemented for a type parameter [E0210]

为什么?假设你的 Components特征是公开的。现在,另一个 crate 中的类型可以实现 Components特征。该类型也可能会尝试实现 Add特征。谁实现Add应该赢,你的 crate 还是其他 crate 的?根据 Rust 当前的一致性规则,另一个 crate 获得此特权。

目前,唯一的选择是重复 impl s,就是使用宏。 Rust 的标准库在很多地方使用宏来避免重复 impl s(特别是对于原始类型),所以你不必觉得脏! :P

关于rust - 为自定义特征提供一揽子特征实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com