Implementing traits
📖 Scenario: You are creating a simple program to describe different animals and their sounds. Each animal can make a sound, but the way they do it depends on the animal type.
🎯 Goal: Build a Rust program that defines a trait called AnimalSound with a method make_sound. Then implement this trait for two structs: Dog and Cat. Finally, call the method to print the sounds each animal makes.
📋 What You'll Learn
Define a trait named
AnimalSound with a method make_sound that returns a string slice.Create two structs:
Dog and Cat.Implement the
AnimalSound trait for both Dog and Cat.In the implementation,
Dog should return "Woof!" and Cat should return "Meow!" from make_sound.Create instances of
Dog and Cat and print their sounds using make_sound.💡 Why This Matters
🌍 Real World
Traits in Rust let you define shared behavior for different types, like animals making sounds. This helps organize code and reuse logic.
💼 Career
Understanding traits is essential for Rust programming jobs, especially when designing flexible and reusable code components.
Progress0 / 4 steps