Search⌘ K

Exercises

Explore practical exercises that help you understand and apply conditionals, boolean logic, and recursion in Rust. This lesson guides you through rewriting code, implementing logical functions, and working with control flow to reinforce your Rust programming skills.

Exercise 1

Rust 1.40.0
fn main() {
if 5 == 5 {
println!("5 == 5 is true");
}
if 5 > 5 {
println!("5 > 5 is true");
}
if 5 >= 5 {
println!("5 >= 5 is true");
}
}
Technical Quiz
1.

What is the output of this program?

A.

5 == 5 is true

5 >= 5 is true

B.

5 == 5 is true

5 > 5 is true

C.

5 >= 5 is true

5 > 5 is true


1 / 1

Exercise 2

Replace all four FIXMEs below with the correct type:

Rust 1.40.0
fn want_apples() -> bool {
true
}
fn want_five() -> bool {
false
}
fn talk_about_fruit() -> bool {
true
}
fn talk_about_numbers() -> bool {
false
}
fn main() {
let fruit: FIXME = if want_apples() {
"apple"
} else {
"banana"
};
let number: FIXME = if want_five() {
5
} else {
6
};
let _x: FIXME = if talk_about_fruit() {
println!("The fruit is {}", fruit);
};
let _y: FIXME = if talk_about_numbers() {
println!("The number is {}", number);
};
}

Exercise 3

Rewrite the program below so it doesn’t use any lets. Reminder: you can put any expression inside a macro call’s parameter list.

Rust 1.40.0
fn comment(apples: i32) {
let message = if apples > 10 {
"lots of"
} else {
"very few"
};
println!("You have {} apples", message);
}
fn main() {
comment(5);
comment(100);
}

Exercise 4

...