Logo

Developer learning path

Rust

Enums in Rust

Enums

58

#description

In Rust programming language, an enum (short for enumeration) is a custom data type that allows you to define a set of named values. Enums give you a way to organize related values into a single type that can be easily understood and managed.

The syntax to define an enum in Rust is as follows:

                    
enum EnumName {
    Value1,
    Value2,
    Value3,
}
                  

where EnumName is the name of the enum and Value1, Value2, and Value3 are the named values or variants of the enum.

Enums in Rust can also have associated data or payloads that can be used to store additional information with a named value.

For example, you can define an enum with different types of status messages like this:

                    
enum Status {
    Ok,
    Error(String),
    Warning(String),
}
                  

Here, the Status enum has three variants: Ok, Error, and Warning. The Error and Warning variants take a String parameter that can be used to store a message associated with the error or warning.

To use an enum in Rust, you can create an instance of the enum by specifying the variant you want to use along with any associated data.

For example:

                    
let my_status = Status::Error("File not found".to_string());
                  

This creates a new instance of the Status enum with the Error variant and associated message "File not found".

Enums are very powerful in Rust and can be used to create complex data types that are robust, efficient, and easy to understand.

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.