Crystal Notes: Enums
Published: 2021-07-30
Intro
Enums group a related number of values and store the values internally as integers. Enums are good to use when the number of values are not too big.
crystal
# Define an Enum.
enum Bike
Specialized
Trek
Cannondale
Factor
end
# Access an Enum.
Bikes::Specialized # => Specialized
# Check the type of an Enum.
typeof(Bike::Specialized) # => Bike
# Access the Enum value
Bike::Specialized.value # => 0
# Check the type of the Enum value
typeof(Bike::Specialized.value) # => Int32
Considerations
- Enums are a type safe alternative to Symbols.
- It is recommended to use Enums whenever possible and only use Symbols for an internal API implementation.
Links
https://www.manning.com/books/rust-in-action
https://www.udemy.com/course/ultimate-rust-crash-course/
https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html
https://doc.rust-lang.org/rust-by-example/custom_types/enum.html