Functions
๋ฌ์คํธ ๋ฒ์ ์ FizzBuzz ํจ์์ ๋๋ค:
A Rust version of the famous FizzBuzz interview question:
fn main() { // ํ๋จ์ ์. ๊ตณ์ด ์๋จ์ ๋ณ๋ ์ ์ธํ ํ์ ์์. // Defined below, no forward declaration needed fizzbuzz_to(20); } fn is_divisible_by(lhs: u32, rhs: u32) -> bool { if rhs == 0 { // ์ฝ๋ ์ผ์ด์ค. // Corner case, early return return false; } // ๋ง์ง๋ง ํํ์์ ๋ฐํ๊ฐ์ ๋ํ๋ ๋๋ค. // The last expression is the return value lhs % rhs == 0 } // `()` ๋ฐํ๊ฐ์ ๋ฐํํ ๊ฐ์ด ์์์ ๋ํ๋ ๋๋ค. // No return value means returning the unit type `()` fn fizzbuzz(n: u32) -> () { match (is_divisible_by(n, 3), is_divisible_by(n, 5)) { (true, true) => println!("fizzbuzz"), (true, false) => println!("fizz"), (false, true) => println!("buzz"), (false, false) => println!("{n}"), } } //๋ฐํ๊ฐ์ด ์๋ ๊ฒฝ์ฐ(`-> ()`) ์๋ต ๊ฐ๋ฅํฉ๋๋ค. // `-> ()` is normally omitted fn fizzbuzz_to(n: u32) { for n in 1..=n { fizzbuzz(n); } }
์ญ์ฃผ
- corner case: ๋ณตํฉ ๊ฒฝ๊ณ ์กฐ๊ฑด. ๋ณ์์ ํ๊ฒฝ์ ์ธ ์์๋ก ์ธํด์ ๋ก์ง์ ๋ฌธ์ ๊ฐ ์๋ ๊ฒฝ์ฐ. ex. ๋๋๊ธฐ ๋ก์ง์์ 0์ผ๋ก ๋๋๋ ๊ฒฝ์ฐ.
- edge case: ๊ฒฝ๊ณ์กฐ๊ฑด. ๋งค๊ฐ๋ณ์ ๊ฐ์ด ๊ทน๋จ์ ์ธ ์ต๋/์ต์๊ฐ(๋ก์ง ์ ํจ๋ฒ์ ๋) ์ด์์ธ ๊ฒฝ์ฐ.
- fizzbuzz: ์ซ์๋ฅผ ์ ๋ ฅ๋ฐ์์ n์ผ๋ก ๋๋๋ฉด fizz, m์ผ๋ก ๋๋๋ฉด buss, ๋๋ค ๋๋๋ฉด fizzbuzz, ์๋๋๋ฉด ์ ๋ ฅ๊ฐ์ ์ถ๋ ฅํ๋ ํ ์คํธ๋ก ์์ฃผ ์ฐ๋ ๋ฌธ์ ์ ๋๋ค. ์์ ์ n,m์ 3,5