Search⌘ K

Exercises

Explore practical exercises to enhance your understanding of Rust traits. Learn to modify functions for flexibility, implement mutable methods, generalize with type parameters, and create custom traits, strengthening your skill in trait usage and generic programming.

Exercise 1

We previously had the program below, and said that we would be polite and not mention someone’s age. Modify the greet function so that it says how old the person is.

Rust 1.40.0
struct Person<Name, Age> {
name: Name,
age: Age,
}
fn greet<Age>(person: &Person<String, Age>) {
println!("Hello, {}", person.name);
}
fn main() {
let alice: Person<String, u32> = Person {
name: "Alice".to_owned(),
age: 30_u32,
};
greet(&alice);
let bob = Person {
name: "Bob".to_owned(),
age: 35_u64,
};
greet(&bob);
}

Exercise 2

Modify the program above so that ...