在Rust 1.3中继承结构的最佳方法是什么? [英] What is the best way to inherit a struct in Rust 1.3?

查看:236
本文介绍了在Rust 1.3中继承结构的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I compile this with Rust 1.3, the compiler tells me that virtual structs have been removed from the language:

struct Foo: Bar {

}


推荐答案

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

Short answer, you can't do inheritance with structs.

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

Instead of inheritance, Rust uses composition. However, you can do inheritance within traits. Traits don't have data, but they can define functions, so you can many of the benefits of inheritance by using them:

trait Foo {
    fn foo(&self);
}

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

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

An implementor of FooBar must implement foo (unless you provide a default implementation).

单向Rust的专业化通常是通过 enums ,这在Rust中非常强大。 Rust的一位开发人员写了一篇关于一篇关于Rust如何处理这些类型的问题。我建议您阅读并阅读官方书籍。

One way Rust does specialization is typically through enums, which are very powerful in Rust. One of the Rust developers wrote a good blog series about how Rust approaches these types of problems. I recommend reading through it as well as reading through the official book.

这篇关于在Rust 1.3中继承结构的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆