Esercizi di Rust
FizzBuzz in Rust
The classic interview warm-up, solved cleanly with match on a tuple.
Cosa imparerai
- 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.
Punti chiave
- (0, 0) means divisible by both.
- _ matches any value.
- Order of the arms matters.
Esempio Rust eseguibile
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 FizzBuzzEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
Tutte le sfide