Control Flow
Conditionals
Examples
-
Works :
if number < 10 { println!("algo"); } else if number < 22 { println!("outra coisa"); } else { println!("outra coisinha"); } -
Does not work :
let number = 3; if number { println!("number was three"); }-
Rust will not automatically try to convert non-Boolean types to a Boolean.
-
Ternary
let number: i32 = if 2 < 3 { 5 } else { 1 }
-
If the
ifandelsearms have value types that are incompatible, you'll get an error.
Loops
Loop
loop {
println!("again!");
if \condicional {
break;
}
}
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter;
}
};
-
break-
Exits the loop.
-
-
continue-
Skip over any remaining code in this iteration of the loop and go to the next iteration.
-
-
Labels
-
You can optionally specify a loop label on a loop that you can then use with
breakorcontinue.let mut count = 0; 'counting_up: loop { println!("count = {count}"); let mut remaining = 10; loop { println!("remaining = {remaining}"); if remaining == 9 { break; } if count == 2 { break 'counting_up; } remaining -= 1; } count += 1; } println!("End count = {count}");
-
While
let mut number = 3;
while number != 0 {
number -= 1;
}
For
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is {}", element);
}
// Creates a sequence of numbers from 1 to 3.
for number in (1..4) {
println!("the value is {}", element);
}
// Same thing
for number in 1..4 {
println!("the value is {}", element);
}