[Rust] 5장 패턴 매칭(Pattern Matching)

1. match 구문

match 구문은 값에 대한 여러 패턴을 검사하고, 일치하는 패턴에 따라 실행하는 코드를 결정합니다.

fn main() {
    let number = 2;
    
    match number {
        1 => println!("One!"),
        2 => println!("Two!"),
        3 => println!("Three!"),
        4 => println!("Four!"),
        5 => println!("Five!"),
        6..=10 => println!("Between Seven and ten"),
        _ => println!("Something else"), // Default Pattern
    }
}

2. 구조체와 열거형 매턴 매칭

Rust의 구조체와 열거형을 사용한 패턴 매칭 수행이 가능합니다.

#[allow(dead_code)]
enum Message {
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
}

fn main() {
    let msg = Message::ChangeColor(255,0,0);

    match msg {
        Message::Quit => println!("Quit!"),
        Message::ChangeColor(r, g, b) => {
            println!("Change Color to Red: {}, green: {}, blue: {}", r,g,b);
        }
        Message::Move { x, y } => {
            println!("Move to x: {}, y: {}", x, y);
        }
    }
}

3. if let 구문 

if let은 특정 패턴에 대해서만 조건부로 실행되는 코드 블록을 작성할 수 있게 해줍니다. 주로 단일 패턴을 처리할 때 유용합니다.

fn main() {
    let some_value = Some(4);

    if let Some(x) = some_value {
        println!("Value: {}", x);
    } else {
        println!("No value found");
    }
}

4. while let 구문 

while let은 반복문에서 특정 패턴이 일치할 때만 반복을 수행할 수 있습니다.

fn main() {
  let mut optional_values = vec![Some(1), Some(2), None, Some(3)];

  while let Some(value) = optional_values.pop() {
    match value {
        Some(v) => println!("Value: {}", v),
        None => println!("No Value"),
    }
  }   
}

5. 패턴 매칭과 기본값

_는 모든 값을 매칭하는 기본 패턴으로, 주로 match 구문에서 마지막에 사용해 모든 경우를 처리합니다.

fn main() {
    let value = 3;

    match value {
        1 => println!("One"),
        2 => println!("Two"),
        3 => println!("Three"),
        _ => println!("Not one and two or three"), // 기본값
    }
}

6. 튜플과 배열 패턴 매칭

Rust의 튜플과 배열에서도 패턴 매칭을 사용할 수 있습니다.

fn main() {
    let tuple = (1, 2, 3);

    match tuple {
        (1, y, z) => println!("First is 1, y: {}, z: {}", y, z),
        (0, _, _) => println!("First is 0"),
        _ => println!("Something else"),
    }

    let array = [1, 2, 3];

    match array {
        [1, ..] => println!("Array starts with 1"),
        _ => println!("Something else"),
    }
}

 

 

GitHub - Koras02/rust-tutorial: https://thinky.tistory.com/category/Back-End/Rust

https://thinky.tistory.com/category/Back-End/Rust. Contribute to Koras02/rust-tutorial development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Rust' 카테고리의 다른 글

[Rust] 7장 모듈  (0) 2025.03.10
[Rust] 6장 에러 처리  (0) 2025.03.08
[Rust] 4장 데이터 타입(Data Types)  (0) 2025.03.02
[Rust] 3장 빌림(Borrowing)  (0) 2025.02.27
[Rust] 2장 Rust의 소유권(Ownership)  (0) 2025.02.26