Cairo의 이넘을 사용하면 여러 개의 이름 붙은 배리언트 중 하나가 될 수 있는 타입을 정의할 수 있어요.
이넘은 '열거'를 뜻하는 enumeration을 줄인 말로, 어떤 데이터가 가질 수 있는 모든 값을 미리 정해진 집합으로 제한해요. enum이 가질 수 있는 값들을 배리언트라고 해요:
#[derive(Drop)]
enum Direction {
North,
South,
East,
West,
}
배리언트를 지정해서 이넘 값을 만들어요:
let my_direction = Direction::North;
let another_direction = Direction::West;
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의 각 갈래는 이넘의 배리언트 중 하나를 처리해요.
이넘 배리언트는 추가 데이터를 담을 수도 있어요:
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."