Rust, lesson 2
A variable gives a name to a value. In Rust you create one with let. Every value has a
type, and the compiler knows every variable's type before the program runs.
Here is Rust's first surprise: variables cannot change unless you say so.
Add mut to make a variable mutable:
Why the default? When most values never change, the few that do stand out, and the compiler
can stop accidental changes. Reach for mut only when you need it.
| Type | Holds | Example |
|---|---|---|
i32 | whole numbers (the default integer) | -7, |
2 exercises to try what you just read.
42i64, u64 | larger signed / unsigned whole numbers | 9_000_000_000 |
usize | sizes and indexes | v.len() |
f64 | numbers with a fraction | 3.75 |
bool | true or false | true |
char | one Unicode character, in single quotes | 'é' |
&str | a piece of text, in double quotes | "hello" |
The u types are unsigned (zero or positive only). Underscores in number literals are
just for readability. Integer overflow is checked: in a debug build, going past a type's limit
stops the program with an error instead of silently wrapping.
Rust usually infers types from the value. You can write the type yourself after a colon, which you must do when the compiler cannot guess:
Rust never converts between number types by itself. Adding an i32 to an f64 is an error.
Convert explicitly with as:
You can declare a new variable with the same name as an earlier one. The new one shadows
the old one. Unlike mut, shadowing can even change the type, which is handy for converting a
value step by step:
Constants use const, need an explicit type, and are written in SCREAMING_SNAKE_CASE. They
must be known at compile time and can be declared outside any function.
Variables and functions use snake_case (high_score). Types use CamelCase. If you create
a variable you do not use, the compiler warns you; start its name with an underscore
(_unused) to say it is deliberate.
The starter declares a player's level and experience points. Make both variables mutable,
then add one level and 250 experience with += before the println!, so the program prints:
Change only what you need; do not just print the expected text.
A fruit stand sells pears. Declare a constant PRICE_PER_PEAR of type f64 with the value
0.75, a variable pears of type i32 set to 6, and compute the total as an f64 using
as. Print:
let lives = 3;
let player = "Kit";
println!("{player} has {lives} lives");let score = 0;
score = 10; // error: cannot assign twice to immutable variablelet mut score = 0;
score += 10;
println!("{score}"); // 10let speed: f64 = 2.5;
let count: u32 = 10;let apples: i32 = 7;
let price = 0.5;
let total = apples as f64 * price; // 3.5
let whole = 3.99_f64 as i32; // 3 (the fraction is cut off)let guess = "42"; // &str
let guess: i32 = 42; // a new variable, now an i32
let guess = guess * 2; // 84const MAX_PLAYERS: u32 = 4;
const PI: f64 = 3.14159;level 5, xp 1250pears: 6
total: 4.50