Rust 練習問題

FizzBuzz in Rust

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

  • 初級
  • 約2分で読めます
  • 実行できるサンプル 1 件
学べること
  • 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.

重要なポイント

  1. (0, 0) means divisible by both.
  2. _ matches any value.
  3. 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 のレビューも受けられます。

すべてのチャレンジ