Small Example
Here is a small example program in Rust:
fn main() { // Program entry pointlet mut x: i32 = 6; // Mutable variable bindingprint!("{x}"); // Macro for printing, like printfwhile x != 1 { // No parenthesis around expressionif x % 2 == 0 { // Math like in other languagesx = x / 2;} else {x = 3 * x + 1;}print!(" -> {x}");}println!();}
Speaker Notes
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
i32to trigger type inference. Try withi8instead and trigger a runtime integer overflow. -
Change
let mut xtolet 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::fmtwhich has the rules of the formatting mini-language. Itโs important that the students become familiar with searching in the standard library.