Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 03 / 21 · THE LANGUAGE

Control flow is a value story.

Follow branches, loops, tuples, and arrays without losing track of types.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

Control flow decides which expression is evaluated next. An if condition must be a bool; Rust does not silently treat a number or a nonempty string as true. An if expression can produce a value, but each possible branch must produce a compatible type. This requirement catches a common design gap: a branch that has not decided what result it means to return.

Loops express three different intentions. loop repeats until an explicit break, while repeats while a condition remains true, and for walks an iterator. A loop can even yield a value through break value. The best choice is the one that makes the stopping condition visible, because a reader must be able to establish that the program will eventually continue.

02 / THE RULES

What Rust is checking.

A tuple groups a fixed number of values, potentially of different types, and position determines each member's meaning. An array has a fixed length and one element type. Both have known shape at compile time. Indexing an array with a bad index can panic at runtime, so iteration is often a clearer way to inspect every element. A slice, introduced later, borrows a view into contiguous elements without owning them.

When tracing a branch, record both its selected path and the type of the value it produces. When tracing a loop, record the state that changes and the exact condition that ends it. That is enough to explain many pieces of Rust code without first memorising every syntax form. The examples below show how ordinary control flow remains tied to the type and ownership rules.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

if, else & boolean logic

An if condition must be a bool; numbers do not convert to truthiness automatically. An if/else can produce a value, provided both branches have compatible types. Logical && and || short-circuit, so the second operand is evaluated only when needed. This lets a guard protect an operation such as division. State conditions in terms of your domain rather than clever punctuation, and test the boundary where the decision changes.

conditions.rs
fn main() {
    let age = 19;
    let status = if age >= 18 { "adult" } else { "minor" };
    let denominator = 0;
    let safe = denominator != 0 && 10 / denominator > 1;
    println!("{status}, safe={safe}");
}
OUTPUT
adult, safe=false
  1. The two status branches both return string slices.
  2. The false first operand prevents division by zero.
  3. Test age 17 and 18 to exercise the boundary.

The boundary: Use parentheses to clarify mixed && and || expressions when the business rule could be misread.

EXAMPLE 02

for, while & loop

Use for to iterate over a range or collection, while for a condition checked before each iteration, and loop when the exit is controlled inside the body. break exits and continue skips to the next iteration. A loop expression can return a value with break value. Ranges such as 0..3 exclude the end, while 0..=3 include it. A simple termination argument is useful even in everyday code: explain what changes on every iteration and why an exit must eventually happen.

loops.rs
fn main() {
    let sum: i32 = (1..=4).sum();
    let mut n = 0;
    let found = loop {
        n += 1;
        if n * n >= 20 {
            break n;
        }
    };
    println!("sum={sum}, first square boundary={found}");
}
OUTPUT
sum=10, first square boundary=5
  1. The inclusive range contributes 1, 2, 3, and 4.
  2. n increases each iteration until its square reaches the threshold.
  3. break n gives the loop its result.

The boundary: An unbounded loop without I/O, waiting, or termination can consume a CPU core. Make its purpose explicit.

EXAMPLE 03

Tuples & arrays

A tuple groups a fixed number of potentially different types. An array holds a fixed number of elements of one type, and its length is part of its type. Destructuring names the useful parts of either shape. Direct indexing panics when an index is out of bounds; get returns an Option so absence can be handled. If size needs to grow dynamically, use a Vec instead. Use a struct rather than a long tuple when field names carry important meaning.

tuples-arrays.rs
fn main() {
    let location = ("Cape Town", -33.9_f64);
    let (city, latitude) = location;
    let samples = [4, 8, 12];
    println!("{city}: {latitude}");
    println!("last={:?}, missing={:?}", samples.get(2), samples.get(9));
}
OUTPUT
Cape Town: -33.9
last=Some(12), missing=None
  1. The tuple stores a string slice and a float.
  2. Destructuring introduces readable names.
  3. get avoids a panic for an unknown index.

The boundary: An array [T; 3] is a different type from [T; 4]. Slices let functions accept either length.

04 / THE CONNECTION

Keep this model.

A branch must make a complete value decision; a loop must make its exit understandable. Rust's type rules make both obligations visible.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.