Implementing Control Flow and Functions in Rust
Course Title: Mastering Rust: From Basics to Systems Programming Section Title: Control Flow and Functions Topic: Implement control flow and functions in Rust through practical exercises.(Lab topic)
Introduction
Now that we have covered the basics of Rust syntax, ownership, borrowing, and lifetimes, it's time to put our knowledge into practice by implementing control flow and functions in Rust through practical exercises. In this topic, we will dive deeper into the world of control flow and functions in Rust and provide hands-on exercises to reinforce your understanding of these concepts.
Exercise 1: Conditional Statements
In this exercise, we will practice using conditional statements to control the flow of our program.
Task: Write a Rust program that takes the age of a person as input and prints out whether they are eligible to vote or not. Assume the voting age is 18.
Solution:
use std::io;
fn main() {
println!("Enter your age:");
let mut age = String::new();
io::stdin().read_line(&mut age).expect("Failed to read line");
let age: i32 = age.trim().parse().expect("Please type a number!");
if age >= 18 {
println!("You are eligible to vote.");
} else {
println!("You are not eligible to vote.");
}
}
Explanation:
- We use the
io
module to read input from the user. - We use a
String
to store the user's input and parse it into ani32
usingparse
. - We use an
if
statement to check if the user's age is greater than or equal to 18. - If true, we print out a message indicating that the user is eligible to vote.
- If false, we print out a message indicating that the user is not eligible to vote.
Exercise 2: Looping Constructs
In this exercise, we will practice using looping constructs to repeat a block of code.
Task: Write a Rust program that prints out the numbers from 1 to 10 using a loop
.
Solution:
fn main() {
let mut i = 1;
loop {
println!("{}", i);
i += 1;
if i > 10 {
break;
}
}
}
Explanation:
- We use a
loop
statement to repeat a block of code. - We use a mutable variable
i
to keep track of the current number. - We use a
break
statement to exit the loop wheni
is greater than 10. - We print out the current number using
println!
.
Exercise 3: Functions
In this exercise, we will practice defining and calling functions in Rust.
Task: Write a Rust program that defines a function add
that takes two integers as input and returns their sum.
Solution:
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let result = add(2, 3);
println!("The result is: {}", result);
}
Explanation:
- We define a function
add
that takes two integers as input and returns their sum. - We use the
->
symbol to indicate the return type of the function. - We use the
fn
keyword to define the function. - We call the function using its name and pass in two arguments.
- We print out the result of the function call using
println!
.
Exercise 4: Closures
In this exercise, we will practice using closures in Rust.
Task: Write a Rust program that defines a closure that takes a string as input and returns a greeting message.
Solution:
fn main() {
let greet = |name: &str| {
println!("Hello, {}!", name);
};
greet("Alice");
greet("Bob");
}
Explanation:
- We define a closure
greet
that takes a string as input and returns a greeting message. - We use the
|
symbol to indicate the input parameters of the closure. - We use the
=>
symbol to indicate the return type of the closure (in this case,()
). - We call the closure using its name and pass in a string argument.
Conclusion
In this topic, we have practiced implementing control flow and functions in Rust through practical exercises. We have covered conditional statements, looping constructs, functions, and closures. By working through these exercises, you should now have a solid understanding of how to control the flow of your program and define reusable blocks of code.
Additional Resources:
- For more information on control flow in Rust, see the Rust documentation.
- For more information on functions in Rust, see the Rust documentation.
- For more information on closures in Rust, see the Rust documentation.
Leave a Comment or Ask for Help:
If you have any questions or need help with any of the exercises, feel free to leave a comment below.
Images

Comments