In Rust, there are three types of control structures: 1. Conditional statements: Conditional statements are used to execute a block of code only when a certain condition is true. Rust has two types of conditional statements: if-else and match.
The if-else statement allows the execution of one of two blocks of code based on a condition. For example:
let x = 5;
if x > 0 {
println!("x is positive");
} else {
println!("x is non-positive");
}
The match statement is used to match a value with different patterns and execute the corresponding block of code. For example:
let x = 5;
match x {
1 => println!("one"),
2 | 3 => println!("two or three"),
4..=10 => println!("four to ten"),
_ => println!("something else"),
}
2. Looping statements: Looping statements are used to execute a block of code repeatedly until a certain condition is met. Rust has two types of looping statements: loop and while.
The loop statement executes a block of code repeatedly until it is interrupted by a break statement. For example:
let mut x = 0;
loop {
if x == 5 {
break;
}
x += 1;
}
println!("x is {}", x);
The while statement executes a block of code repeatedly while a certain condition is true. For example:
let mut x = 0;
while x < 5 {
x += 1;
}
println!("x is {}", x);
3. Control Flow Statements: Control Flow Statements are used to change the order of execution of a block of code. Rust has two types of control flow statements: break and continue.
The break statement is used to terminate a loop prematurely. For example:
let mut x = 0;
while x < 10 {
if x == 5 {
break;
}
x += 1;
}
println!("x is {}", x);
The continue statement is used to skip the current iteration of a loop and start the next one. For example:
for x in 0..10 {
if x % 2 == 0 {
continue;
}
println!("{}", x);
}
These control structures allow Rust developers to write more efficient and readable code.