C++ 允许类子类型化,这非常方便,因为您可以将为基类实现的函数与派生类一起使用。 Rust 似乎没有这样的东西。该功能似乎在某个时候可用,但此后已被删除。这在 Rust 中是不可能的吗?如果是这样,有没有计划拥有这个功能?
我想做的是定义一个继承自另一个结构的结构,在 C++ 中它看起来像:
struct Base {
int x;
int y;
void foo(int x, int y) { this->x = x; this->y = y; }
}
struct Derived: public Base {
...
}
void main() {
Derived d;
d.foo();
}
在我看来,在 Rust 中你必须写这样的东西才能使相同的功能可用于所有“派生”结构:
struct Base<T> {
x: i32,
y: i32,
derived: T
}
impl<T> Base<T> {
fn foo(&mut self, x: i32, y: i32) {
self.x = x;
self.y = y;
}
}
我想做一个 impl<T> for Base<T>
将产生大量相同功能的副本,因此组合并不是真正的选择。
我应该指出,选择上述实现的原因很简单,因为它允许更安全的向上转换版本,无论如何我都需要这样做。
最佳答案
使用组合而不是继承。
struct Base {
x: u8,
y: u8,
}
impl Base {
fn foo(&mut self, x: u8, y: u8) {
self.x = x;
self.y = y;
}
}
struct Derived {
base: Base,
}
impl Derived {
fn foo(&mut self, x: u8, y: u8) {
self.base.foo(x, y);
}
}
fn main() {
let mut d = Derived { base: Base { x: 1, y: 3 } };
d.foo(5, 6);
}
Rust 可以更好地使组合在键盘上像继承一样简单。有 a RFC旨在提供更好的东西,以及之前的讨论1 , 2 .
I think doing an
impl<T> for Base<T>
will produce a ton of copies of the same function, so composition isn't really an option.
我不确定此语法试图显示为 Base
的内容没有通用类型。确实,对于每个具体的类型参数集,泛型类型都是单态化,但我看不出/不知道这与 C++ 有何不同。我认为 Rust 版本会稍微轻一些,因为你不能从 Derived
向上转换到 Base
因此编译器不必维护这些不变量。
所有这些都假设有一些代码可以重用。在许多情况下,您最好对一个接口(interface)进行编程,该接口(interface)用 traits 表示。在 rust 中。您可以结合这两种方法 — 将可重用的小代码提取为组件,将它们捆绑在一起形成聚合,并为聚合类型实现特征。
关于rust - Rust 中的类子类型化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894776/