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 리뷰를 받을 수 있습니다.
모든 챌린지