rsRustPrimer
< Back to module

Language basics

Control flow

if is an expression: it produces a value. It replaces the ternary operator, which does not exist in Rust. Both branches must have the same type, and the condition must be an actual bool (no "truthy" values like 0 or 1).

rust
fn main() {
let mtm: f64 = -250.0;
let side = if mtm >= 0.0 { "on nous doit" } else { "nous devons" };
println!("{side} {}", mtm.abs());
}

Three loops. loop runs forever until a break (which can return a value). while runs while a condition holds. for walks over a collection or a range: by far the most used.

rust
fn main() {
// 0..5 exclut 5, 0..=5 l'inclut
for year in 1..=3 {
println!("année {year}");
}
let mut capital = 100.0;
let mut years = 0;
while capital < 200.0 {
capital *= 1.07;
years += 1;
}
println!("doublé en {years} ans");
let mut attempts = 0;
let found = loop {
attempts += 1;
if attempts == 3 {
break attempts * 10;
}
};
println!("{found}");
}

match compares a value against patterns, in order. It must be exhaustive: every possible case has to be covered, otherwise the code does not compile. The _ pattern catches everything else.

rust
fn rating_bucket(score: u32) -> &'static str {
match score {
0 => "défaut",
1..=3 => "spéculatif",
4..=6 => "moyen",
_ => "solide",
}
}
fn main() {
println!("{}", rating_bucket(5));
}
We will revisit match in depth with enums, where it becomes the central tool of the language.

Your turn

Using a for loop over the array, count how many scenarios have a strictly positive MtM.

src/main.rs
fn main() {
let mtms = [120.0, -40.0, 0.0, 75.5, -10.0, 300.0];
let mut positive = 0;
// boucle ici
println!("{positive} scénarios positifs"); // 3
}