// Start of Selection
enum Color { Red, Green, Blue }enum Option<T> { Some(T), None }match some_option {
Some(value) => println!("값: {}", value),
None => println!("값이 없습니다."),
}if let Some(value) = some_option {
println!("값: {}", value);
} else {
println!("값이 없습니다.");
}패턴 매칭은 Rust의 강력한 기능 중 하나로, 다양한 데이터 구조를 간결하고 효율적으로 처리 \
match 키워드를 사용하여 값이 특정 패턴과 일치하는지 검사하고, 각 패턴에 대해 다른 동작 수행 가능
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u32 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
},
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
let coin = Coin::Penny;
println!("The value of the coin is {} cents.", value_in_cents(coin));
}
위 예제에서 Coin 열거형(enum)을 정의하고, 각 동전의 값을 반환하는 value_in_cents 함수를 구현했습니다. \
match 표현식을 사용하여 coin 값이 어떤 동전인지 검사하고, 그에 따라 다른 값을 반환합니다.
패턴 매칭은 단순한 값 비교 외에도 다양한 상황에서 유용하게 사용될 수 있습니다.
fn main() {
let pair = (0, -2);
match pair {
(0, y) => println!("First is zero and y is {}", y),
(x, 0) => println!("x is {} and second is zero", x),
_ => println!("It is a different pair"),
}
}
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 0, y: 7 };
match p {
Point { x: 0, y } => println!("On the y axis at {}", y),
Point { x, y: 0 } => println!("On the x axis at {}", x),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let msg = Message::ChangeColor(0, 160, 255);
match msg {
Message::Quit => println!("The Quit variant has no data to destructure."),
Message::Move { x, y } => println!("Move in the x direction {} and in the y direction {}", x, y),
Message::Write(text) => println!("Text message: {}", text),
Message::ChangeColor(r, g, b) => println!("Change the color to red {}, green {}, and blue {}", r, g, b),
}
}
패턴 매칭은 Rust의 안전성과 가독성을 높이는 중요한 기능입니다. 다양한 데이터 구조를 다룰 때 패턴 매칭을 활용하면 코드의 명확성과 효율성을 크게 향상시킬 수 있습니다.