Menu
Coddy logo textTech

데이터를 포함한 Enum

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 14번째.

Rust의 기본 열거형을 사용하면 Direction::North 또는 Status::Active처럼 고정된 변형 집합을 가진 타입을 정의할 수 있습니다. 하지만 Rust의 열거형은 그보다 훨씬 강력합니다. 각 변형은 자체 데이터를 포함할 수 있으므로, 열거형은 실제 상황을 모델링할 때 매우 유연합니다.

서로 다른 message 유형이 서로 다른 정보를 전달하는 메시징 시스템을 생각해 보세요. 텍스트 message에는 콘텐츠가 있고, 이동 명령에는 좌표가 있으며, 종료 신호에는 아무것도 없습니다. Rust에서는 이 모든 것을 하나의 enum으로 나타낼 수 있습니다:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(u8, u8, u8),
}

각 variant는 서로 다른 형태를 가집니다. Quit는 데이터를 보유하지 않습니다. 단지 신호일 뿐입니다.

Move는 이름이 지정된 필드를 사용하는 구조체와 유사한 구문을 사용합니다. Write는 튜플 구문을 사용하여 하나의 String을 저장합니다. ChangeColor는 RGB 구성 요소를 나타내는 세 개의 값을 저장합니다.

이러한 변형의 인스턴스를 생성하는 방법은 다음과 같습니다.

let m1 = Message::Quit;
let m2 = Message::Move { x: 10, y: 20 };
let m3 = Message::Write(String::from("Hello"));
let m4 = Message::ChangeColor(255, 128, 0);

이 접근 방식의 장점은 m1, m2, m3, m4가 모두 같은 타입인 Message라는 것입니다. 이들을 같은 컬렉션에 저장하거나, 같은 함수에 전달하거나, 하나의 함수에서 어떤 variant든 반환할 수 있습니다. enum은 각 variant에 필요한 구체적인 정보를 보존하면서 서로 다른 데이터 형태를 하나의 타입으로 통합합니다.

challenge icon

챌린지

쉬움

data가 포함된 enum을 사용하여 다양한 유형의 alert를 나타내는 notification system을 만들어 보겠습니다. 각 notification type은 서로 다른 정보를 포함합니다. 일부는 message를 포함하고, 일부는 숫자 값을 포함하며, 일부는 단순한 신호입니다.

코드를 구성하기 위해 두 개의 파일을 만듭니다.

  • notification.rs: 세 가지 variant를 가진 public Notification enum을 Define합니다.
    • Alert: 하나의 String message를 holds합니다(tuple syntax).
    • Reminder: named fields를 holds합니다: title(String) 및 minutes(u32)
    • Dismiss: data는 holds하지 않고 단순한 신호만 나타냅니다.
  • main.rs: notification module을 가져오고 각 variant의 instance를 하나씩 만듭니다. 그런 다음 세 variant가 모두 같은 type이지만 서로 다른 data를 포함한다는 것을 보여 주기 위해 각 notification에 대한 정보를 Print합니다.

Print할 때는 debug formatting({:?})을 사용하여 각 notification을 표시합니다. 이 방식으로 Print할 수 있도록 enum에 Debug trait을 derive해야 합니다.

출력에는 세 notification이 모두 각자 한 줄에 표시되어야 합니다.

Alert("{message}")
Reminder { title: "{title}", minutes: {minutes} }
Dismiss

예를 들어, alert message가 "Server down"이고, title이 "Meeting"이며 30 minutes인 reminder가 있다면 출력은 다음과 같습니다.

Alert("Server down")
Reminder { title: "Meeting", minutes: 30 }
Dismiss

세 개의 inputs를 받습니다. alert message, reminder title, 그리고 reminder minutes입니다.

직접 해보기

mod notification;

use notification::Notification;

fn main() {
    // 입력 읽기
    let mut alert_message = String::new();
    std::io::stdin().read_line(&mut alert_message).expect("Failed to read line");
    let alert_message = alert_message.trim().to_string();

    let mut reminder_title = String::new();
    std::io::stdin().read_line(&mut reminder_title).expect("Failed to read line");
    let reminder_title = reminder_title.trim().to_string();

    let mut minutes_input = String::new();
    std::io::stdin().read_line(&mut minutes_input).expect("Failed to read line");
    let reminder_minutes: u32 = minutes_input.trim().parse().expect("Failed to parse minutes");

    // TODO: alert_message를 사용하여 Alert 알림 생성

    // TODO: Create a Reminder notification using reminder_title and reminder_minutes

    // TODO: Dismiss 알림 생성

    // TODO: 디버그 포맷팅 {:?}을 사용하여 각 알림 출력
    // 각 알림은 자체 줄에 출력되어야 합니다
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러