rustHow to create enum from int in Rust
Enums in Rust are used to define a set of named constants. To create an enum from an integer, you can use the From trait. This trait allows you to convert an integer into an enum variant. The following ## Code example shows how to create an enum from an integer:
enum Color {
Red,
Green,
Blue,
}
let color_int = 2;
let color = Color::from(color_int);
println!("The color is: {:?}", color);
Output example
The color is: Blue
Explanation
The ## Code example starts by defining an enum called Color with three variants: Red, Green, and Blue. Then, an integer is assigned to the variable color_int. The From trait is used to convert the integer into an enum variant. Finally, the println! macro is used to print the enum variant to the console.
Relevant links
Related
- How to create enum from string in Rust
- How to use enum as hashmap key in Rust
- How to create enum from number in Rust
- How to use fmt for enum in Rust
- How to declare enum in Rust
- How to compare enum in Rust
- How to serialize enum in Rust
- How to loop through enum in Rust
- How to cast enum in Rust
- Get certain enum value in Rust
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...