Tsallaka zuwa abun ciki
Justice Tech School

If, Loop, While and For

if is an expression and can return a value. loop repeats forever until break, while checks a condition and for walks over ranges and collections.

Example
let n = 7;
let kind = if n % 2 == 0 { "even" } else { "odd" };
println!("{}", kind);
for i in 1..=3 {
    println!("i = {}", i);
}
let mut c = 3;
while c > 0 {
    c -= 1;
}
let v = vec![10, 20, 30];
for x in &v {
    println!("{}", x);
}

Result

odd
i = 1
i = 2
i = 3
10
20
30

Exercise

Count 1 to 3 inclusive.

for i in 13 {}

Quiz Test

Is if an expression in Rust?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.