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

查看:25
本文介绍了在 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中进行继承.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天全站免登陆