Enums in Cairo allow you to define a type that can be one of several named variants.
Enums, short for enumerations, limit all possible values of some data to a predefined set.
The possible values of an enum are called variants:
#[derive(Drop)]
enum Direction {
North,
South,
East,
West,
}
Create enum values by specifying the variant:
let my_direction = Direction::North;
let another_direction = Direction::West;
Use match to handle different enum variants:
match my_direction {
Direction::North => println!("Going north!"),
Direction::South => println!("Going south!"),
Direction::East => println!("Going east!"),
Direction::West => println!("Going west!"),
}
Each arm of the match handles one variant of the enum.
Enum variants can hold additional data:
struct Location {
x: u32,
y: u32,
}
enum Message {
Text: ByteArray,
Number: u32,
Location: Location,
}
Pattern match to extract the data:
match msg {
Message::Text(content) => println!("Text: {}", content),
Message::Number(val) => println!("Number: {}", val),
Message::Location(Location { x, y }) => println!("Position: ({}, {})", x, y),
}
In this exercise you'll be generating weather reports for a local news station.
You'll start with some stubbed functions and the following enum:
#[derive(Drop, Clone, PartialEq, Debug)]
pub enum WeatherCondition {
Sunny,
Rainy,
Cloudy,
Stormy
}
You will need to format a weather report like "Today is <CONDITION> with a temperature of <TEMPERATURE> degrees Celsius.".
You'll need to implement the function that outputs the correct weather conditions.
For example, the below snippet demonstrates an expected output for the get_weather_report function for a "rainy" day.
get_weather_report(WeatherCondition::Rainy, "25")
// Returns: "Today is RAINY with a temperature of 25 degrees Celsius."
And for a "sunny" day:
get_weather_report(WeatherCondition::Sunny, "30")
// Returns: "Today is SUNNY with a temperature of 30 degrees Celsius."
Sign up to Exercism to learn and master Cairo with 25 concepts68 exercises, and real human mentoring, all for free.