본문 바로가기
Personal-Study/Rust

[Rust 문서 읽기] 6. Enums and Pattern Matching (열거형과 패턴 매칭)

by Aaron-Kim 2023. 2. 5.

The Rust Programming Language

- Defining an Enum

  - enum gives us a way of saying a value is one of a possible set of values

  - Enum Values

    - we can put data directly into each enum variant

    - the name of each enum variant that we define also becomes a function
      that constructs an instance of the enum

    - each variant can have different types and amounts of associated data

    - we can put any kind of data inside an enum variant
       ex) strings, numeric types, structs, another enum, etc.

    - we're able to define methods on enums using impl keyword

  - The Option Enum and Its Advantabes Over Null Values

    - The Option type encodes the very common scenario
       in which a value could be something or it could be nothing

    - eliminating the risk of incorrectly assuming a not-null value
      helps you to be more confident in your code

   

fn main() {
    let four = IpAddrKind::V4(127, 0, 0, 1);
    let six = IpAddrKind::V6(String::from("::1"));

    dbg!(four);
}

#[derive(Debug)]
enum IpAddrKind {
    V4(u8, u8, u8, u8),
    V6(String),
}

 

- The match Control Flow Construct

  - Patterns That Bind to Values

 

fn main() {
    value_in_cents(Coin::Quarter(UsState::Alaska));
}

#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => {
            println!("Lucky penny!");
            1
        }
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {:?}", state);
            25
        }
    }
}

 

  - Matching with Option<T>

 

fn main() {
    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);

    println!("{:?} {:?} {:?}", five, six, none);
}

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

 

  - Matches Are Exhaustive

  - Catch-all Patterns and the _ Placeholder

 

fn main() {
    let dice_roll = 9;
    match dice_roll {
        3 => add_fancy_hat(),
        7 => remove_fancy_hat(),
        _ => reroll(),
    }
}

fn add_fancy_hat() {}
fn remove_fancy_hat() {}
fn reroll() {}

 

- Concise Control Flow with if let

 

fn main() {
    let config_max = Some(3u8);
    // match config_max {
    //     Some(max) => println!("The maximum is configured to be {}", max),
    //     _ => (),
    // }

    if let Some(max) = config_max {
        println!("The maximum is configured to be {}", max);
    } else {
        println!("hi");
    }
}

 

- Summary


Enums and Pattern Matching (영어)

열거형과 패턴 매칭 (한국어)

반응형

댓글