Course › Week 1 · Basics and ownership › Day 2 · lesson 2 of 42 · 15 min reading + 60–90 min practice
Variables, types and functions
Immutable by default, one fixed type per value, and functions whose last expression is the return value.
On this page
Today has seven small ideas. Take them one at a time: read one, type its program, run it, then move on. None of them is hard on its own; what is new is that Rust is strict about every one of them.
The thread through all seven: in PHP, many decisions happen while the program runs. In Rust, they are made before it runs, by the compiler.
1. Variables are immutable by default
let creates a variable. Once it has a value, that value cannot change:
fn main() {
let nights = 3;
println!("{nights} nights");
nights = 4;
println!("{nights} nights");
}
error[E0384]: cannot assign twice to immutable variable `nights`
--> src/main.rs:5:5
|
2 | let nights = 3;
| ------ first assignment to `nights`
...
5 | nights = 4;
| ^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut nights = 3;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `hello` (bin "hello") due to 1 previous errorThe compiler tells you exactly what to do: add mut. Immutable by default means that when you read let x = … in a long function, you know x never changes further down. You only have to watch the few variables marked mut.
2. mut: a variable that can change
fn main() {
let mut nights = 3;
println!("{nights} nights");
nights = 4;
println!("{nights} nights");
}
3 nights
4 nights3. Shadowing: a new variable with the same name
You can declare a variable again with let. The new one hides (“shadows”) the old one. It is a new variable, so it can even have a different type:
fn main() {
let input = " 3 "; // text, as it came from a form
let input = input.trim(); // still text, without the spaces
let input = input.len(); // now a number: how many characters
println!("{input}");
}
1Shadowing is for transforming a value step by step, when you have no use for the old version. mut is for a value that changes over time, like a counter. You will see both in real code.
4. Every value has one type
The types you will use every day
| Type | Holds | PHP closest |
|---|---|---|
i32, i64 | Signed whole numbers, 32 or 64 bits. i32 is the default for a literal like 3. | int |
u32, u64 | Unsigned: zero and up. Counts, IDs, cents. | int |
usize | Unsigned, the size of a memory address. Lengths and indexes always use it. | int |
f64 | A 64-bit float. Never for money (Pattern Playbook’s first scene shows why). | float |
bool | true or false | bool |
char | One Unicode character, in single quotes: 'é' | no equivalent |
Rust works out the type, and you can write it
After a name, : type says the type. Most of the time the compiler infers it, and you only write it when it cannot tell or when you want to be explicit:
fn main() {
let nights = 3; // i32, inferred
let price_cents: u64 = 15_010; // written: u64. Underscores make big numbers readable.
let is_weekend: bool = true;
println!("{nights} nights at {price_cents} cents, weekend: {is_weekend}");
}
3 nights at 15010 cents, weekend: trueTypes never mix on their own
PHP happily multiplies an int by a float, or a number by a numeric string. Rust does not convert anything without being asked, even between two integer types:
fn main() {
let nights: u32 = 3;
let price_cents: u64 = 15_010;
let billable_nights: u64 = nights;
println!("{}", price_cents * billable_nights);
}
error[E0308]: mismatched types
--> src/main.rs:5:32
|
5 | let billable_nights: u64 = nights;
| --- ^^^^^^ expected `u64`, found `u32`
| |
| expected due to this
|
help: you can convert a `u32` to a `u64`
|
5 | let billable_nights: u64 = nights.into();
| +++++++
For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello` (bin "hello") due to 1 previous errorThe fix is to convert on purpose. Converting a smaller unsigned type to a bigger one can never lose anything, and u64::from(nights) says so. The compiler suggests .into(), which does the same conversion; from reads more clearly while you learn. (You will also see nights as u64: it works too, but as silently cuts numbers that do not fit, so prefer from when it exists.)
fn main() {
let nights: u32 = 3;
let price_cents: u64 = 15_010;
let billable_nights: u64 = u64::from(nights);
println!("{}", price_cents * billable_nights);
}
45030Integer division stays an integer
fn main() {
let guests = 7;
let rooms = 2;
println!("{}", guests / rooms); // 3, not 3.5
println!("{}", guests % rooms); // 1 left over
}
3
1In PHP, 7 / 2 is 3.5. In Rust, dividing two integers gives an integer. This is the source of many off-by-one bugs in code ported from PHP.
5. Functions
Typed parameters, typed return
Parameter types are required, always. The return type comes after ->. And the last expression of a function, written without a semicolon, is its return value:
fn total_cents(price_cents: u64, nights: u64) -> u64 {
price_cents * nights
}
fn main() {
let total = total_cents(15_010, 3);
println!("{total}");
}
45030return total; also works, and you use it to return early. But the normal style is the last expression, with no return and no semicolon.
One semicolon changes the meaning
A semicolon turns an expression into a statement, and a statement produces nothing. So this function returns nothing, while it promised a u64:
fn total_cents(price_cents: u64, nights: u64) -> u64 {
price_cents * nights;
}
fn main() {
let total = total_cents(15_010, 3);
println!("{total}");
}
error[E0308]: mismatched types
--> src/main.rs:1:50
|
1 | fn total_cents(price_cents: u64, nights: u64) -> u64 {
| ----------- ^^^ expected `u64`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | price_cents * nights;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello` (bin "hello") due to 1 previous error() in the message is the “unit” type: the value of nothing, like void. The compiler spotted the stray semicolon and says to remove it.
6. if is an expression
In Rust, if produces a value, so it replaces PHP’s ternary ?:. Both branches must have the same type.
fn main() {
let nights = 9;
let stay = if nights >= 7 {
"long stay"
} else {
"short stay"
};
println!("{stay}");
if nights > 28 {
println!("needs a monthly contract");
} else if nights >= 7 {
println!("gets the weekly discount");
} else {
println!("standard price");
}
}
long stay
gets the weekly discountThe condition must be a bool
PHP treats 0, "" and [] as false. Rust has no “truthy”: the condition must be a bool.
fn main() {
let unread = 3;
if unread {
println!("you have messages");
}
}
error[E0308]: mismatched types
--> src/main.rs:4:8
|
4 | if unread {
| ^^^^^^ expected `bool`, found integer
For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello` (bin "hello") due to 1 previous errorSay what you mean: if unread > 0.
7. Loops
for over a range
1..=nights is a range from 1 to nights, included. 1..nights would stop before nights.
fn main() {
let nights = 3;
for night in 1..=nights {
println!("night {night}");
}
}
night 1
night 2
night 3for over an array
An array has a fixed length, written in its type: [u64; 3] is three u64s.
fn main() {
let nightly_cents: [u64; 3] = [15_010, 15_010, 18_000]; // Friday is more expensive
let mut total: u64 = 0;
for price in nightly_cents {
total += price;
}
println!("{total}");
}
48020while and loop
while runs as long as its condition is true. loop runs forever until a break, and break can hand back a value:
fn main() {
let mut attempt = 0;
let result = loop {
attempt += 1;
if attempt == 3 {
break attempt * 10; // the loop's value
}
};
println!("succeeded on attempt {attempt}, result {result}");
}
succeeded on attempt 3, result 30You will meet loop again for retries and for reading input until it ends.
Coming from PHP
The same booking total, side by side. Everything the PHP version decides while running, Rust decides while compiling.
<?php
function totalCents(int $priceCents, int $nights): int
{
return $priceCents * $nights;
}
$nights = 3;
$nights = "3"; // allowed: same variable, now a string
echo totalCents(15010, $nights); // works: "3" is juggled to 3 (unless strict_types=1)
In Rust, the second $nights line would need a new let (shadowing), and the string could never be passed where a number is expected. declare(strict_types=1) is PHP’s step toward the same idea; in Rust it is always on, and it covers every type, not only function arguments.
PracticeThe Book ch. 3, Rustlings variables, functions, if, primitive types
Read chapter 3 of the Book.
In Rustlings: 01_variables, 02_functions, 03_if, 04_primitive_types, then quiz1.
Exercise: the cleaning fee
Write a function stay_total(nightly_cents: u64, nights: u32, cleaning_cents: u64) -> u64 that returns the nightly price times the nights, plus the cleaning fee, except that stays of 7 nights or more get the cleaning for free. Use if as an expression. Print the result for 3 nights and for 7 nights at 15,010 cents a night and 4,500 cents of cleaning.
Show the solution
fn stay_total(nightly_cents: u64, nights: u32, cleaning_cents: u64) -> u64 {
let cleaning = if nights >= 7 { 0 } else { cleaning_cents };
nightly_cents * u64::from(nights) + cleaning
}
fn main() {
println!("{}", stay_total(15_010, 3, 4_500));
println!("{}", stay_total(15_010, 7, 4_500));
}
49530
105070Remember
- Variables are immutable unless marked
mut; shadow withletto transform a value step by step. - Types never convert on their own: convert on purpose with
u64::from(). - A function returns its last expression; a stray semicolon turns it into
().
Tomorrow is the most important day of the week: ownership, the idea that makes Rust different from every language you know.