Lesson 3
Variables, functions and control flow
Learn to store values, transform data, choose paths, and repeat actions with Rust.
Four pieces for giving instructions
A useful program needs to remember data, apply rules, make decisions, and repeat work. Before looking at Rust syntax, we can arrange those tasks into four pieces:
- Storean amount of energy
- Calculatehow to transform it
- Decidewhether energy remains
- Repeatthe operation for several turns
Rust expresses those four ideas with variables, functions, if, and loops.
You do not need to know how each value is stored in memory yet: here, the goal
is to learn how to read the program’s path.
Inference and annotations
Rust needs to know the type of every value, but it can often infer it:
| Code | Type Rust recognizes | What it represents |
|---|---|---|
let energy = 4; |
integer, usually i32 |
a number without decimals |
let temperatura = 18.5; |
decimal, usually f64 |
a number with decimals |
let activo = true; |
bool |
true or false |
let simbolo = 'R'; |
char |
one Unicode character |
You can write let energy: i32 = 4; when the type choice matters or when you
want to make it visible. You do not need to annotate every variable.
Choosing a loop
| Form | Use it when… | Key idea |
|---|---|---|
for |
you have a sequence or range to visit | advances automatically through every element |
while |
you need to repeat while a condition is true | checks the condition before each pass |
loop |
you want to repeat until you choose to leave with break |
has no implicit exit condition |
In this introduction you will practise for, the most direct option when a
range describes the number of steps. Module 1 will go deeper into while,
loop, break, continue, and loop labels.
Before running: predict
For remaining_energy(3, 2), the variable starts at 3. The 0..2 range
produces two passes: after the first, 2 remains; after the second, 1 remains.
For remaining_energy(2, 5), the final three passes still check the condition,
but no longer subtract because energy has reached 0.
The exercise uses non-negative initial energy and turn counts.
Predicting the state pass by pass is a simple way to review a loop before asking the compiler to run it.
Exercise 01 · Energy workshop
Make the energy last for as many turns as possible.
The starter already connects the four pieces from this lesson: a mutable variable, a for loop, a condition, and a return value. Complete the missing update.
Objective
Complete remaining_energy for non-negative inputs. Each turn consumes one unit while energy remains. The result must not drop below zero, and zero turns must preserve the initial energy.
Implement
Replace `todo!` with `energy -= 1;`.
Function 01
Calculate remaining energy
Complete the structured body: subtract one unit when the condition allows entry.
/// Calculates the energy remaining after several turns.
pub fn remaining_energy(initial_energy: i32, turns: i32) -> i32 {
let mut energy = initial_energy;
for _turn in 0..turns {
if energy > 0 {
todo!("subtract one unit of energy");
}
}
energy
}Check
Run three visible cases and use the diagnostic to correct the code.
Visible tests
Modify the code before running the tests.
Help
View progressive hints or compare with the solution.
/// Calculates the remaining energy without allowing a non-negative input to drop below zero.
#[must_use]
pub fn remaining_energy(initial_energy: i32, turns: i32) -> i32 {
let mut energy = initial_energy;
for _turn in 0..turns {
if energy > 0 {
energy -= 1;
}
}
energy
}
// Playground entry point for this example.
fn main() {
println!("{}", remaining_energy(3, 2));
println!("{}", remaining_energy(2, 5));
println!("{}", remaining_energy(4, 0));
}Summary
letcreates immutable variables by default;let mutpermits explicit changes.- Rust can infer basic types, while an annotation such as
: i32fixes the choice. - A function declares parameter and return types; its final expression returns the value.
ifrequires a Boolean condition and runs exactly one of its branches.forvisits sequences and ranges;..excludes the end and..=includes it.whilerepeats according to a condition andloopcontinues until abreak; both are covered in depth later.