为什么 Rust 有 struct 和 enum? [英] Why does Rust have struct and enum?

查看:48
本文介绍了为什么 Rust 有 struct 和 enum?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 的枚举是代数数据类型.据我所知,这似乎包含了 struct 是什么.需要保留它的 struct 有什么不同?

Rust's enums are algebraic datatypes. As far as I can tell this seems to subsume what struct is. What is different about struct that necessitates keeping it?

推荐答案

首先,你是对的,在语义上 enum 严格优于 struct它可以表示,因此 struct 有点多余.

First of all, you are correct that semantically enum is strictly superior to the struct as to what it can represent, and therefore struct is somewhat redundant.

然而,这里还有其他因素在起作用.

However, there are other elements at play here.

  • 易用性:enum 中的值只能通过匹配(直接)访问;与访问 struct 字段的易用性形成对比.您可以为每个字段编写访问器,但这真的很麻烦.

  • ease of use: the values within an enum can only be accessed (directly) through matching; contrast with the ease of use of accessing a struct field. You could write accessors for each and every field, but that is really cumbersome.

区别:enum 是标记联合,struct 具有固定布局;我们(程序员)通常喜欢给事物贴上标签,因此可以为不同的功能赋予不同的名称.

distinction: an enum is a tagged union, a struct has a fixed-layout; we (programmers) generally like to put labels on things, and therefore giving different names to different functionality can be appreciated.

在我看来,struct 因此是语法糖.我通常更喜欢精益和吝啬,但一点点糖可以大大增加可以简洁表达的内容.

As I see it, struct is therefore syntactic sugar. I usually prefer lean and mean, but a bit of sugar can go a long way in increasing what can be represented tersely.

这篇关于为什么 Rust 有 struct 和 enum?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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