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 withi8
instead and trigger a runtime integer overflow. - Change
let mut x
tolet 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.