Struct, Enum और Trait
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. आसान