1
First, let's discuss control structures in Rust.
1. **If Expressions**:
The syntax for an if expression is similar to other C-like languages. The conditional is followed by a block of code for the true branch. Let's try a simple example:
```rust
fn main() {
let x = 5;
if x > 1 {
println!("x is greater than 1");
}
}
```
You can also add an optional else branch to handle the false case.
```rust
fn main() {
let x = 5;
if x > 1 {
println!("x is greater than 1");
} else {
println!("x is not greater than 1");
}
}
```
2. **Loops**:
Rust offers several looping constructs, including loops that iterate over a sequence, loop, while, and for.
* **Loop**:
A basic **loop** with a break statement to exit.
```rust
fn main() {
let mut counter = 0;
loop {
if counter == 10 {
break;
}
counter += 1;
println!("counter = {}", counter);
}
}
```
* **While**:
A **while** loop, similar to loops in other C-like languages.
```rust
fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
}
```
* **For**:
A **for** loop is used to iterate over collections, such as arrays, slices, and vectors.
```rust
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
```
liked the content? then leave your comment or handshake on the post. thanks
You must log in or # to comment.


