Rust

Control flow

The ability to run some code depending on whether a condition is true and to run some code repeatedly while a condition is true are basic building blocks in most programming languages. The most common constructs that let you control the flow of execution of Rust code are if expressions and loops.

If

Filename: src/main.rs

fn main() {
let number = 3;
if number < 5 {
println!("Condition was true");
} else {
println!("Condition was false");
}
}

Loop

Filename: src/main.rs

fn main() {
loop {
println!("Condition was true");
}
}

Returning Values from Loops

Filename: src/main.rs

fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}

While

Filename: src/main.rs

fn main() {
let mut number = 3;
while number != 0 {
println!("Condition was true");
number -= 1;
}
println!("LIFTOFF!!!");
}

Filename: src/main.rs

fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}

For

Filename: src/main.rs

fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}

Filename: src/main.rs

fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}