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