Skip to main content Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.
Navigation Resources
© 2026 BraveProgrammer. All rights reserved.
Control Flow | Rust Fundamentals lesson | BraveProgrammer
Courses / Rust Fundamentals Control Flow
Control flow statements direct the execution path of your program based on conditions.
If Expressions
Rust's if is an expression, not just a statement:
let number = 6 ;
if number % 2 == 0 {
println! (\
"Even\");
} else if number % 3 == 0 {
println!(\"Divisible by 3\");
} else {
println!(\"Odd\");
}
If expressions return values:
let condition = true ;
let value = if condition { 5 } else { 6 };
println! (\"Value: {}\", value); // 5
Arms must return the same type.
Loops
Infinite Loop let mut count = 0 ;
loop {
count += 1 ;
println! (\"Count: {}\", count);
if count == 5 {
break;
}
}
While Loop let mut count = 0 ;
while count < 5 {
println! (\"Count: {}\", count);
count += 1;
}
For Loop Iterates over ranges and collections:
for i in 0 ..5 {
println! (\"i = {}\", i); // 0 to 4
}
// Inclusive range
for i in 0..=5 {
println!(\"i = {}\", i); // 0 to 5
}
// Over collections
let numbers = [1, 2, 3];
for num in numbers {
println!(\"Number: {}\", num);
}
Loop Labels Break or continue outer loops:
'outer : loop {
for i in 0 ..10 {
if i == 5 {
break 'outer ;
}
}
}
Break with Values let mut count = 0 ;
let result = loop {
count += 1 ;
if count == 10 {
break count * 2 ;
}
};
println! (\"Result: {}\", result);
Practical Example fn main () {
let numbers = [1 , 3 , 5 , 6 , 7 , 8 ];
for num in numbers {
if num % 2 == 0 {
println! (\"First even: {}\", num);
break;
}
}
// Validate input
let mut attempts = 0;
while attempts < 3 {
println!(\"Try again\");
attempts += 1;
}
// Grade calculator
let score = 85;
let grade = if score >= 90 {
'A'
} else if score >= 80 {
'B'
} else if score >= 70 {
'C'
} else {
'F'
};
println!(\"Grade: {}\", grade);
}
Make it stick Practice what you've learned 1 quiz · 1 practical test · Optional activities from Rust Fundamentals Browse activities Quiz 1 Course Quiz 3 questions · Pass mark: 70% Start quiz Practical test 1 Hello Rust Program Create a simple Rust program that prints "Hello, Rust!" Start practical test