Cairo 的 enum 讓你可以定義一種型別,這種型別的值可以是數個具名變體中的一個。
enum 是 enumeration 的簡稱,它把某筆資料所有可能的值限定在一組預先定義好的集合裡。
enum可能的值稱為變體:
#[derive(Drop)]
enum Direction {
North,
South,
East,
West,
}
指定變體就能建立 enum 值:
let my_direction = Direction::North;
let another_direction = Direction::West;
用 match 處理不同的 enum 變體:
match my_direction {
Direction::North => println!("Going north!"),
Direction::South => println!("Going south!"),
Direction::East => println!("Going east!"),
Direction::West => println!("Going west!"),
}
match 的每個分支處理 enum 的一種變體。
enum 的變體可以攜帶額外的資料:
struct Location {
x: u32,
y: u32,
}
enum Message {
Text: ByteArray,
Number: u32,
Location: Location,
}
用模式比對把資料取出來:
match msg {
Message::Text(content) => println!("Text: {}", content),
Message::Number(val) => println!("Number: {}", val),
Message::Location(Location { x, y }) => println!("Position: ({}, {})", x, y),
}
在這個練習中,你會為地方新聞台產生天氣報告。
你會從一些尚未實作的函式和下面這個列舉開始:
#[derive(Drop, Clone, PartialEq, Debug)]
pub enum WeatherCondition {
Sunny,
Rainy,
Cloudy,
Stormy
}
你需要把天氣報告格式化成像"Today is <CONDITION> with a temperature of <TEMPERATURE> degrees Celsius."這樣。
你需要實作能輸出正確天氣狀況的函式。
舉例來說,下面的程式片段展示了get_weather_report函式在雨天時的預期輸出。
get_weather_report(WeatherCondition::Rainy, "25")
// Returns: "Today is RAINY with a temperature of 25 degrees Celsius."
而晴天時則是:
get_weather_report(WeatherCondition::Sunny, "30")
// Returns: "Today is SUNNY with a temperature of 30 degrees Celsius."