Cairoのenumを使うと、いくつかの名前付きバリアントのうちのどれか1つをとる型を定義できます。
enumはenumerationの略で、あるデータがとり得る値を、あらかじめ決められた集合に限定します。このenumがとり得る値のことをバリアントと呼びます。
#[derive(Drop)]
enum Direction {
North,
South,
East,
West,
}
enumの値は、バリアントを指定して作ります。
let my_direction = Direction::North;
let another_direction = Direction::West;
enumのバリアントごとに処理を分けるには、matchを使います。
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のバリアントを1つずつ処理します。
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),
}
この演習では、地元のニュース局のための天気予報を生成します。
まずは、いくつかのスタブ関数と、次のenumから始めます。
#[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."