Control Flow
if, loop, while, and for
If Statements
If you've been using Java, if
statements in Rust will look really familiar, with just a few less parentheses.
fn main() {
let number = 3;
if number < 5 {
println!("number isn't very big");
} else if > 9 {
println!("oh wow that is big");
} else {
println!("i guess it's somewhere in the middle");
}
}
The expression to the right of the if
must evaluate to a boolean. Rust does not convert non-boolean types to boolean values (unlike a language like Ruby).
You can also use if
on the right side of a let
statement:
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
One key thing: the results must be of the same type. So while the above works, this doesn't:
fn main() {
let condition = true;
let number = if condition {
5
} else {
"six"
};
println!("The value of number is: {}", number);
}
Loops
Rust has three types of loops: loop
, while
, and for
. Let's try them all!
Loop
We looked into this basic type of loop during Guessing Game. As a refresher, this is what a basic loop looks like:
fn main() {
loop {
println!("again!");
}
}
Caveat: if you run this, it will just print again!
over and over again. Make sure to use break;
within a condition to leave the loops and avoid an endless loop!
While (Conditional Loops)
More often, you are likely to use a while
loop. Instead of using loop
and if
, you can just use a single while
like this:
fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number = number - 1;
}
println!("LIFTOFF!!!");
}
This loop will loop three times until number is zero. At that point, it will break out of the loop and print out the next line. This is equivalent to:
fn main() {
let mut number = 3;
loop {
if number == 0 { break; }
println!("{}!", number);
number = number - 1;
}
println!("LIFTOFF!!!");
}
For
While you can loop through a collection with a while
loop like this:
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index = index + 1;
}
}
It's a little bulky though. Let's do the same thing with a for
loop:
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
Instead of having to parse out what the index is doing (and having to define it), the for
loop allows us to write code that's a little closer to English:
for element in array do this { statement }
We can also redo that countdown with a for loop and make it even more clear and concise:
fn main() {
for number in (1..4).rev() {
println!("{}!", number);
}
println!("LIFTOFF!!!");
}
Last updated