Rust 等同于 C++ 的虚函数是什么?

What is the Rust equivalent to C++'s virtual functions?

我正在尝试在 Rust 中实现一些像 class 中的 C++ 虚函数一样工作的东西,我会有一个包含数据的基本结构,然后我会保留一些未定义的函数,如下例:

class A {
    int stuff;
public:
    virtual void foo(int a, int b) = 0;
    void function_that_calls_foo() { /*...*/ foo(1, 2); /*...*/ }
}

class B: public A { void foo(int a, int b) { /* ... */ } }

我试图用函数指针来实现它,但没有成功。我可以使用具有 A 函数的特征,并在另一个 class 上实现 A,但我会丢失结构的数据。在 Rust 中实现这种东西的最佳(最快?)方法是什么?

struct A {
    ...
}

impl A {
    fn function_that_calls_foo(&self) {
        ...
        self.foo(a, b);
        ...
    }
}

struct B {
    a: A;
}

impl B {
    fn xxx(&self) {
        a.function_that_calls_foo(1, 2);
    }

    fn foo(&self, a: i32, b: i32) {...}
}

keep some functions undefined

我正在添加隐式 "and have some functions that call that to-be-defined function"。

作为, use a trait:

trait Foo {
    fn foo(&self, a: i32, b: i32) -> i32;

    fn function_that_calls_foo(&self) {
        println!("{}", self.foo(1, 2));
    }
}

然后您可以为 Base 实现特征:

struct Base {
    stuff: i32,
}

impl Foo for Base {
    fn foo(&self, a: i32, b: i32) -> i32 {
        self.stuff + a + b
    }
}

一样,Rust没有继承,所以使用组合:

struct Base {
    stuff: i32,
}

impl Base {
    fn reusable(&self) -> i32 {
        self.stuff + 1
    }
}

struct Alpha {
    base: Base,
    modifier: i32,
}

impl Foo for Alpha {
    fn foo(&self, a: i32, b: i32) -> i32 {
        (self.base.reusable() + a + b) * self.modifier
    }
}

您也可以通过采用受类型参数约束的 generic 来结合这两个概念。


我会强烈支持 。使用新语言应该涉及检查新范例。以代码重用为目的的继承通常不是一个好主意,即使在支持它的语言中也是如此。相反,创建更小的构建块并将它们组合在一起。