Search⌘ K

Exercises

Explore hands-on exercises to deepen your understanding of Rust's structs and ownership rules. Learn to modify code, manage values without let statements, and handle function returns effectively. These exercises help you apply concepts practically and fix common issues in Rust programming.

We'll cover the following...

Exercise 1

Modify this program to get rid of all let statements. Remember: struct expressions are just another kind of expression!

Rust 1.40.0
struct Fruit {
apples: i32,
bananas: i32,
}
fn increase_fruit(fruit: Fruit) -> Fruit {
let fruit = Fruit {
apples: fruit.apples * 2,
bananas: fruit.bananas * 3,
};
fruit
}
fn new_fruit() -> Fruit {
let fruit = Fruit {
apples: 10,
bananas: 5,
};
fruit
}
fn print_fruit(fruit: Fruit) {
println!("You have {} apples and {} bananas", fruit.apples, fruit.bananas);
}
fn main() {
let fruit = new_fruit();
let fruit = increase_fruit(fruit);
print_fruit(fruit);
}

Exercise 2

We originally wanted to ...