Variant Payloads

๋‹ค์–‘ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง„ variants๋ฅผ ์—ด๊ฑฐํ˜•์— ์ •์˜ํ•˜๊ณ , match ๊ตฌ๋ฌธ์„ ์ด์šฉํ•ด ์ด๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:

You can define richer enums where the variants carry data. You can then use the match statement to extract the data from each variant:

enum WebEvent {
    PageLoad,                 // Variant without payload
    KeyPress(char),           // Tuple struct variant
    Click { x: i64, y: i64 }, // Full struct variant
}

#[rustfmt::skip]
fn inspect(event: WebEvent) {
    match event {
        WebEvent::PageLoad       => println!("page loaded"),
        WebEvent::KeyPress(c)    => println!("pressed '{c}'"),
        WebEvent::Click { x, y } => println!("clicked at x={x}, y={y}"),
    }
}

fn main() {
    let load = WebEvent::PageLoad;
    let press = WebEvent::KeyPress('x');
    let click = WebEvent::Click { x: 20, y: 80 };

    inspect(load);
    inspect(press);
    inspect(click);
}

์—ญ์ฃผ

  • ์—ด๊ฑฐํ˜• ์š”์†Œ์— ๊ฐ’์„ ํฌํ•จํ•˜๋„๋ก(์˜ˆ์‹œ) ์„ ์–ธํ•ด์„œ match ๋ฌธ์—์„œ ์—ด๊ฑฐํ˜•์˜ ํƒ€์ž…์— ๋”ฐ๋ผ ๋™์ž‘ํ•˜๋„๋ก ๋งŒ๋“ค์–ด์ง„ ์˜ˆ์‹œ์ž…๋‹ˆ๋‹ค