Enums as Structs in Rust
Enums as Structs
80
Enums in Rust are a way to represent a finite set of possible values. Enum types in Rust can also contain data structures within them, which makes them extremely powerful.
Enums as structs simply refers to the fact that enums in Rust can contain fields, similar to how structs can contain fields. This allows enums to be more versatile and represent more complex data types.
Let's look at an example:
enum Person { Name(String), Age(u8), Address { street: String, city: String, state: String }, }
In this example, the Person
enum has three variants - Name
, Age
, and Address
. The Name
variant contains a single field of type String
, the Age
variant contains a single field of type u8
, and the Address
variant contains three fields of type String
.
With this setup, we can create instances of the Person
enum that store specific types of data.
For example:
let person1 = Person::Name(String::from("Alice")); let person2 = Person::Age(30); let person3 = Person::Address { street: String::from("123 Main St."), city: String::from("New York"), state: String::from("NY") };
In this way, enums in Rust can act as structured data types that can contain complex data structures. This opens up a whole range of possibilities when it comes to modeling data in Rust.
March 27, 2023