Logo

Developer learning path

Rust

Enums as Structs in Rust

Enums as Structs

80

#description

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

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.