How to map enum values to integers (i32, u64) in Rust?
Hello colleagues! I've just started learning Rust and encountered a problem that seems simple, but I can't find an elegant solution.
I have an enum `Color` that describes colors:
```rust
enum Color {
Red,
Green,
Blue,
}
```
I want to assign an integer value to each variant, so that, for example, `Red` corresponds to 0, `Green` to 1, `Blue` to 2. And then I need:
1. Get a number from an enum variant (e.g., from `Color::Green` get `1`).
2. Do the reverse conversion: from a number (e.g., `2`) get the variant `Color::Blue`.
In C++ or C# I would just write `(int)color` or `(Color)2`. In Python I would use a dictionary. But in Rust everything is stricter with types.
I tried using `as`:
```rust
let c = Color::Red;
let n =
No answers yet.
Log in to leave an answer