Small Example

๋Ÿฌ์ŠคํŠธ๋กœ ์ž‘์„ฑ๋œ ์ž‘์€ ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.

Here is a small example program in Rust:

fn main() {              // ํ”„๋กœ๊ทธ๋žจ ์ง„์ž…์ (Program entry point)
    let mut x: i32 = 6;  // ๊ฐ€๋ณ€ ๋ณ€์ˆ˜ ํ• ๋‹น(Mutable variable binding)
    print!("{x}");       // printf์™€ ๊ฐ™์€ ์ถœ๋ ฅ ๋งคํฌ๋กœ(Macro for printing, like printf)
    while x != 1 {       // ํ‘œํ˜„์‹์—๋Š” ๊ด„ํ˜ธ ์—†์Œ(No parenthesis around expression)
        if x % 2 == 0 {  // ์ˆ˜ํ•™์‹ ๊ธฐํ˜ธ๋Š” ๋‹ค๋ฅธ์–ธ์–ด์™€ ์œ ์‚ฌ(Math like in other languages)
            x = x / 2;
        } else {
            x = 3 * x + 1;
        }
        print!(" -> {x}");
    }
    println!();
}
๊ฐ•์˜ ์ฐธ์กฐ ๋…ธํŠธ

์ด ์ฝ”๋“œ๋Š” ์ฝœ๋ผ์ธ  ์ถ”์ธก(Collatz conjecture)์œผ๋กœ ๊ตฌํ˜„๋ฉ๋‹ˆ๋‹ค:
๋ฐ˜๋ณต๋ฌธ์ด ์–ธ์ œ๋‚˜ ์ข…๋ฃŒ์กฐ ๊ฒƒ์ด๋ผ๊ณ  ๋ฏฟ์ง€๋งŒ ์ฆ๋ช…๋œ ๊ฒƒ์€ ์•„๋‹™๋‹ˆ๋‹ค. ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜๊ณ  ์‹คํ–‰ํ•ด ๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

ํ‚คํฌ์ธํŠธ:

  • ๋ชจ๋“  ๋ณ€์ˆ˜๊ฐ€ ์ •์ ์œผ๋กœ ์ž…๋ ฅ๋จ์„ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค. i32๋ฅผ ์‚ญ์ œํ•˜์—ฌ ์œ ํ˜• ์ถ”๋ก ์„ ์œ ๋ฐœํ•ด ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. i32๋Œ€์‹  i8๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ ๋Ÿฐํƒ€์ž„ ์˜ค๋ฒ„ํ”Œ๋กœ๋ฅผ ์œ ๋ฐœํ•ด ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • let mut x๋ฅผ let x๋กœ ์ˆ˜์ •ํ•˜์—ฌ ์ปดํŒŒ์ผ ์˜ค๋ฅ˜์— ๋Œ€ํ•ด ํ† ๋ก ํ•ฉ๋‹ˆ๋‹ค.
  • ์ธ์ˆ˜๊ฐ€ ํฌ๋งท ๋ฌธ์ž์—ด๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ print!์—์„œ์˜ ์ปดํŒŒ์ผ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•จ์„ ์–ธ๊ธ‰ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์Šต๋‹ˆ๋‹ค.
  • ๋‹จ์ผ ๋ณ€์ˆ˜๋ณด๋‹ค ๋ณต์žกํ•œ ์‹์„ ์ธ์‡„ํ•˜๋ ค๋ฉด {}์„(๋ฅผ) ์ž๋ฆฌ ํ‘œ์‹œ์ž๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ณด์—ฌ ์ค๋‹ˆ๋‹ค.
  • ํ•™์ƒ๋“ค์—๊ฒŒ ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๋ณด์—ฌ์ฃผ๊ณ , ๋ฏธ๋‹ˆ ์–ธ์–ด ํ˜•์‹์˜ ๊ทœ์น™์ด ์žˆ๋Š” std::fmt๋ฅผ ๊ฒ€์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค. ํ•™์ƒ๋“ค์ด ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—์„œ ๊ฒ€์ƒ‰ํ•˜๋Š” ๊ฒƒ์— ์ต์ˆ™ํ•ด์ง€๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค.

The code implements the Collatz conjecture: it is believed that the loop will always end, but this is not yet proved. Edit the code and play with different inputs.

Key points:

  • Explain that all variables are statically typed. Try removing i32 to trigger type inference. Try with i8 instead and trigger a runtime integer overflow.
  • Change let mut x to let x, discuss the compiler error.
  • Show how print! gives a compilation error if the arguments donโ€™t match the format string.
  • Show how you need to use {} as a placeholder if you want to print an expression which is more complex than just a single variable.
  • Show the students the standard library, show them how to search for std::fmt which has the rules of the formatting mini-language. Itโ€™s important that the students become familiar with searching in the standard library.