0
0
Rustprogramming~30 mins

Default method implementations in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Default method implementations
📖 Scenario: Imagine you are creating a simple system to describe different animals and their sounds. Some animals have a common sound, but others might have their own unique sound.
🎯 Goal: You will create a trait with a default method implementation for making a sound. Then, you will implement this trait for different animals, using the default sound for some and a custom sound for others.
📋 What You'll Learn
Create a trait called Animal with a method make_sound that returns a String.
Provide a default implementation for make_sound that returns "Some generic animal sound".
Create a struct called Dog.
Create a struct called Cat.
Implement the Animal trait for Dog using the default make_sound method.
Implement the Animal trait for Cat with a custom make_sound method returning "Meow".
Create instances of Dog and Cat.
Print the sounds made by both animals.
💡 Why This Matters
🌍 Real World
Traits with default methods let you define common behavior for many types, while allowing specific types to customize that behavior.
💼 Career
Understanding traits and default implementations is key for writing clean, reusable Rust code in many software projects.
Progress0 / 4 steps
1
Create the Animal trait with a default method
Write a trait called Animal with a method make_sound that returns a String. Provide a default implementation for make_sound that returns "Some generic animal sound".
Rust
Hint

Use trait to define Animal. Inside, define fn make_sound(&self) -> String with a default body returning String::from("Some generic animal sound").

2
Create structs Dog and Cat
Create two empty structs called Dog and Cat.
Rust
Hint

Use struct Dog; and struct Cat; to create empty structs.

3
Implement Animal for Dog and Cat
Implement the Animal trait for Dog using the default make_sound method. Then implement Animal for Cat with a custom make_sound method that returns "Meow".
Rust
Hint

For Dog, write impl Animal for Dog {} to use the default method. For Cat, write impl Animal for Cat and override make_sound to return String::from("Meow").

4
Create instances and print their sounds
Create a variable dog as an instance of Dog and a variable cat as an instance of Cat. Then print the result of calling make_sound on both dog and cat.
Rust
Hint

Create dog and cat variables with Dog and Cat. Use println!("{}", dog.make_sound()) and similarly for cat.