Lesson 3

Variables, functions and control flow

Learn to store values, transform data, choose paths, and repeat actions with Rust.

Level
Intro
Duration
18 min
Updated

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:

  1. 01 · VariableStorean amount of energy
  2. 02 · FunctionCalculatehow to transform it
  3. 03 · ConditionDecidewhether energy remains
  4. 04 · LoopRepeatthe 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.

Workshop state

  • STATE · energyinitial value: 4
  • RULE · let mutchange is declared
  • RESULT · variable readyit can be updated later
01 / 04LET · IMMUTABLE BY DEFAULT

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.

0/1correct

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.

01

Implement

Replace `todo!` with `energy -= 1;`.

Function 01

Calculate remaining energy

Unchanged

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
}
02

Check

Run three visible cases and use the diagnostic to correct the code.

subtracts, stops at zero, and accepts zero turns
Compiler

Modify the code before running the tests.

03

Help

View progressive hints or compare with the solution.

Run an attempt to unlock the solution.

Summary

  • let creates immutable variables by default; let mut permits explicit changes.
  • Rust can infer basic types, while an annotation such as : i32 fixes the choice.
  • A function declares parameter and return types; its final expression returns the value.
  • if requires a Boolean condition and runs exactly one of its branches.
  • for visits sequences and ranges; .. excludes the end and ..= includes it.
  • while repeats according to a condition and loop continues until a break; both are covered in depth later.

Sources