rustHow to cast enum in Rust
In Rust, you can cast an enum to a number using the as
keyword. For example, if you have an enum Fruit
with variants Apple
, Orange
, and Banana
, you can cast it to an integer like this:
enum Fruit {
Apple,
Orange,
Banana,
}
let my_fruit = Fruit::Apple;
let my_fruit_as_int = my_fruit as i32;
The output of this code would be my_fruit_as_int = 0
. This is because the variants of the enum are assigned values starting from 0.
You can also cast a number to an enum using the from
keyword. For example, if you have the same enum Fruit
as before, you can cast an integer to it like this:
let my_int = 2;
let my_int_as_fruit = Fruit::from(my_int);
The output of this code would be my_int_as_fruit = Fruit::Banana
.
Helpful links
Related
- How to use enum as hashmap key in Rust
- How to loop through enum in Rust
- How to use fmt for enum in Rust
- How to print enum in Rust
- Using enum in json in Rust
- How to create enum from number in Rust
- Get certain enum value in Rust
- Enum as string in Rust
- Enum as u8 in Rust
- How to create enum from int in Rust
More of Rust
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to match the end of a line in a Rust regex?
- How to get a capture group using Rust regex?
- How to create a new Rust HashMap with values?
- How to use regex with bytes in Rust?
- How to get an entry from a HashSet in Rust?
- How to create a HashMap of HashMaps in Rust?
See more codes...