Ejercicios de Rust

FizzBuzz in Rust

The classic interview warm-up, solved cleanly with match on a tuple.

  • Principiante
  • 2 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • 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.

Puntos clave

  1. (0, 0) means divisible by both.
  2. _ matches any value.
  3. Order of the arms matters.

Ejemplo ejecutable de Rust

Rust
Ejecutar código →
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(" "));
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Practica

Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.

¿Terminaste esta lección?

Márcala como aprendida para seguir tu progreso.

Practica con un reto

Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.

Todos los retos