구조체, 열거형, 트레이트
Rust Pattern Matching with match
Compare a value against values, ranges, tuples and guards, and let the compiler check you covered everything.
배울 내용
- match arms
- Ranges, | and guards
- if let
match n
0"zero"1 | 2 | 3"small"4..=9"medium"_"large"The first pattern that fits wins
match compares a value with a list of patterns and runs the first one that fits. Patterns can be single values, several values, ranges, tuples, or a name that catches everything else.
1 | 2 | 3 matches any of the three values and 4..=9 matches a range. n if n < 0 is a guard: the pattern matches only when the condition is true. _ catches everything that is left. if let is a short match for a single pattern.
핵심 포인트
- 1 | 2 | 3 matches any of the three.
- 4..=9 matches a range.
- _ catches everything else.
실행 가능한 Rust 예제
Rust
main.rs
fn classify(n: i32) -> &'static str {
match n {
0 => "zero",
1 | 2 | 3 => "small",
4..=9 => "medium",
n if n < 0 => "negative",
_ => "large",
}
}
fn main() {
for n in [0, 2, 7, -5, 42] {
println!("{n}: {}", classify(n));
}
let point = (0, 8);
match point {
(0, y) => println!("on the y axis at {y}"),
(x, 0) => println!("on the x axis at {x}"),
(x, y) => println!("at ({x}, {y})"),
}
let maybe = Some(3);
if let Some(value) = maybe {
println!("got {value}");
}
}
0: zero
2: small
7: medium
-5: negative
42: large
on the y axis at 8
got 3연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Triangle Classification Classify three side lengths as invalid, equilateral, isosceles, or scalene. 쉬움
- Point Quadrant Find which quadrant a point lies in. 쉬움