If-statements in Rust do not need parentheses around their conditions, like with Java or C:
fn main() {
let i = 5;
if i == 0 {
println!("Zero!"); // Compiles, does not execute
} else {
println!("😔");
}
}
The result of an if-statement can immediately be assigned to a variable in Rust:
fn main() {
let i = 5;
let j = if i > 2 {10} else {0};
println!("{}", i + j);
}
For-loops in Rust are syntactically similar to if-statements, as they also do not need parentheses:
fn main() {
for i in 0..10 { // For-loop with range
println!("{}", i*i);
}
let arr = vec![5; 10]; // Creates vector with 10 elements, each element being the int 5
for j in arr { // For-loop with iterable structure, like a vector
println!("{}", j*j);
}
}
As can be seen in the above example, ranges in Rust are defined with a double full stop between the lower and upper bounds. Variable i acts as an iterator for all integers between 0 and 10 (including 0, but excluding 10 - Rust ranges exclude the last element by default), while variable j iterates for all elements of arr.
Whether a Rust range includes or excludes the ending element can be specified:
fn main() {
let mut v: Vec<i32> = Vec::new();
for i in 0..=100 { // Equals sign means that range is fully inclusive
v.push(i);
}
println!("{:?}", v);
}
Rust also has a third kind of loop, simply defined with the keyword loop, that is designed to run infinitely. The only way for the loop to finish execution is manually, with the break keyword:
fn main() {
let mut x = 0;
loop {
x += 1;
if x == 20 {
break;
}
}
println!("{}", x)
}
Exercise:
Using a for-loop, while-loop, or the infinite loop explained above (or all three!), make the function below print the fifteen times table up to 50: