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?
structs can be used to model cars and define state. methods and associated functions can be used to specify their behaviour. enums can be used to specify range of allowed values for a custom data type. traits can be used to describe shared behaviours across user-defined data types.
An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }
Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using example_struct. field syntax.
To define a struct, we enter the keyword struct and name the entire struct. A struct's name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call fields.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With