Now that we know some basics of Rust and how to import and use packages called crates and now we will be taking a look at Rust Control Flow. Things like If statements, Loops etc. If statements and loops in Rust have a syntax simillar to Python but added with curly braces. Now lets get to it.
If-Else Statements
If-Else statements in Rust are the same as any other language but with a small difference. In other languages like C and C++ we use to contain conditions in paranthesis but in Rust we write conditions the way we write in Python and after than curly braces and inside those we write the code that needs to be executed if it meet the conditions.
fn main() {
let num = 8;
if num > 20 {
println!("Bigger than 20");
} else if num > 10 {
println!("Smaller than 20 But Bigger than 10");
} else {
println!("Smaller Than 10");
}
}
We can use else statements and if statements with else statements to control the flow of the program. We can also return a value from if statements and store them in variables like so.
fn main() {
let age = 50;
let id_old = if age > 40 {
true
} else {
false
}
}
Switch Stetements
Rust does not have a switch keyword but there is one way to do switch statements in Rust and that is using match. Match looks for a condition and will run the statement inside it which meets that condition.
fn main() {
let age = 20;
match age {
15 => println!("15"),
16 => println!("16"),
17 => println!("17"),
18 => println!("18"),
n if n > 65 => println!("Retired"),
_ => println!("Invalid") // Else Statement
}
}
Loops
Now next thing in Control Flow is Loops. Infinite Loops in Rust is quite simple than any other language that I know of so far. You just use loop keyword and it will start infinite loop.
fn main() {
let mut i = 0;
loop {
if i == 10 {
break;
}
println!("{}", i);
i += 1;
}
}
you can capture the output from a loop assigning the loop to a variable the same way we did with the if and else statements.
let mut i = 0;
let high_num = loop {
if i == 100 {
break i;
}
i += 1;
};
While Loops
Same as anyother language.
let mut i = 0;
while i < 65 {
i += 1;
}
For Loops
Rust do for loops a little different than other languages.
for i in (0..100) {
println!("{}", i);
}
For loops will by default increment the counter by one but if you want you can use step_by()
to step as many times as you want.
for i in (0..100).step_by(2) {
println!("{}", i); // 0, 2, 4, 6, 8, ...
}