inheritance - 在 Rust 1.3 中继承结构的最佳方式是什么?

标签 inheritance struct rust

当我用 Rust 1.3 编译它时,编译器告诉我 virtual 结构已从语言中删除:

struct Foo: Bar {

}

最佳答案

简短的回答,你不能用结构做继承。

Rust 不使用继承,而是使用组合。但是,您可以traits 内进行继承。 .特征没有数据,但它们可以定义函数,因此您可以通过使用它们来获得继承的许多好处:

trait Foo {
    fn foo(&self);
}

trait FooBar: Foo {
    fn foobar(&self);
}

FooBar 的实现者必须实现foo(除非您提供默认实现)。

Rust 进行专门化的一种方式通常是通过 enums,这在 Rust 中非常强大。一位 Rust 开发人员写道 a good blog series about how Rust approaches these types of problems .我建议通读它以及通读官方书籍。

关于inheritance - 在 Rust 1.3 中继承结构的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35328392/

相关文章:

android - 继承和泛型 java android

专门化泛型协议(protocol)的 Swift 协议(protocol)

rust - 是否有单一生产者多消费者 channel 的图书馆?

rust - 设置 GTK 应用程序标题

c# - 在基类中使用动态关键字和调用泛型方法导致 StackOverflowException

java - 如何将基类中的字段很好地复制到派生类中?

c++ - 似乎无法将 void* 强制转换为 C++ 中的结构

struct - ColdFusion 中 cfcatch 的类型

C 中具有大型结构的缓存位置

rust - "does not necessarily outlive the lifetime"问题