rustHow to declare enum in Rust
Enums in Rust are declared using the enum
keyword, followed by the name of the enum and a set of variants in curly braces. Each variant can optionally have associated data, such as a string or integer. For example, the following code declares an enum called Color
with three variants: Red
, Green
, and Blue
. Each variant has an associated integer value.
enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
The code above will create an enum with three variants, each with an associated integer value. The output of this code will be a type called Color
that can be used to store values of type Color
.
output example
Color
The enum can then be used to store values of type Color
in a variable. For example, the following code creates a variable called my_color
and assigns it the value Color::Red
.
let my_color = Color::Red;
The enum can also be used to match against values. For example, the following code will print out a message depending on the value of my_color
.
match my_color {
Color::Red => println!("The color is red"),
Color::Green => println!("The color is green"),
Color::Blue => println!("The color is blue"),
}
Output example:
The color is red
Enums in Rust are a powerful tool for creating types that can store multiple values. They can be used to store values of a specific type, as well as to match against values.
Helpful links
Related
- How to use enum as hashmap key in Rust
- How to lowercase enum in Rust
- How to use fmt for enum in Rust
- How to create enum from number in Rust
- How to print enum in Rust
- Using enum in json in Rust
- How to create enum from string in Rust
- Get certain enum value in Rust
- Enum as string in Rust
- Enum as u8 in Rust
More of Rust
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to parse a file with Rust regex?
- How to use regex lookahead in Rust?
- How to use regex captures in Rust?
- How to use regex to match a group in Rust?
- How to match the end of a line in a Rust regex?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
See more codes...