Rust अभ्यास
FizzBuzz in Rust
The classic interview warm-up, solved cleanly with match on a tuple.
आप क्या सीखेंगे
- match on (n % 3, n % 5)
- The _ pattern
- map and join
1 to 6
11
22
Fizz3
44
Buzz5
Fizz6
Two remainders, four cases
Print the numbers from 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
Matching on the tuple (n % 3, n % 5) checks both remainders at once, and _ means any value. map calls fizzbuzz for every number of the range and join puts the results on one line.
मुख्य बातें
- (0, 0) means divisible by both.
- _ matches any value.
- Order of the arms matters.
चलने योग्य Rust उदाहरण
Rust
main.rs
fn fizzbuzz(n: u32) -> String {
match (n % 3, n % 5) {
(0, 0) => String::from("FizzBuzz"),
(0, _) => String::from("Fizz"),
(_, 0) => String::from("Buzz"),
_ => n.to_string(),
}
}
fn main() {
let line: Vec<String> = (1..=15).map(fizzbuzz).collect();
println!("{}", line.join(" "));
}
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzzअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज