https://www.recurse.com/manual
An enumeration, also referred to as enum is a simultaneous definition of a nominal enumerated type as well as a set of constructors, that can be used to create or pattern-match values of the corresponding enumerated type.
enum Direction {
Up,
Down,
Left,
Right
}
enum Direction {
Up,
Down,
Left,
Right
}
let move = Direction::Left;
enum KeyboardControls { Quit, KeyPress { w: bool, a: bool, s: bool, d: bool },
Direction(String), Move(i32, i32), }
enum KeyboardControls { Quit, KeyPress { w: bool, a: bool, s: bool, d: bool },
Direction(String), Move(i32, i32), }
struct Quit; struct KeyPress { w: bool, a: bool, s: bool, d: bool } struct Direction(String); struct Move(i32, i32);
enum Direction { Up, Down, Left, Right } impl Direction { fn move_character(&self) { println!("{:?}", self); } }
Rust doesn't have a concept of "null". The problem with null values is that if you try to use a null value as a not-null value, you’ll get an error of some kind. Because this null or not-null property is pervasive, it’s extremely easy to make this kind of error.
However, Rust has an enum that can encode the concept of a value being present or absent. This enum is Option<T>
enum Option<T> { Some(T), None, }
<T> means the Some variant of the Option enum can hold one piece of data of any type.
The compiler can’t infer the type that the Some variant will hold by looking only at a None value.
enum Colors { Red, Blue, Green, Yellow } fn hex_from_color(colors: Colors) -> String { match colors { Colors::Red => String::from("#FF0000"), Colors::Blue => String::from("#0000FF"), Colors:: Green => String::from("#00FF00"), Colors::Yellow => String::from("#FFFF00") } }
enum Colors { Red, Blue, Green, Yellow } fn hex_from_color(colors: Colors) -> String { match colors { Colors::Red => String::from("#FF0000"), Colors::Blue => String::from("#0000FF"), Colors:: Green => String::from("#00FF00"), Colors::Yellow => String::from("#FFFF00") } }
enum ShadesOfBlue { AliceBlue, Turqoise } enum Colors { ... Blue(ShadesOfBlue), } fn hex_from_color(colors: Colors) -> String { match colors { Colors::Blue(shade) => { println!("Shade of blue: {:?}", shade); String::from("#0000FF") } } }
Rustlings
https://github.com/rust-lang/rustlings
Rustlings
$ rustlings run enums1
$ rustlings hint enums1
Complete Exercises
Enum 1, 2, 3