Defining traits
📖 Scenario: You are creating a simple program to describe animals. Each animal can make a sound. You want to define a common behavior for all animals using a trait.
🎯 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 for each animal and print their sounds.
📋 What You'll Learn
Define a trait named
AnimalSound with a method make_sound that returns a &str.Create a struct called
Dog.Create a struct called
Cat.Implement the
AnimalSound trait for both Dog and Cat.In the
main function, create instances of Dog and Cat.Print the sounds made by the dog and cat using the
make_sound method.💡 Why This Matters
🌍 Real World
Traits in Rust are like contracts that say what behavior a type must have. This is useful when you want different types to be used interchangeably if they share the same behavior.
💼 Career
Understanding traits is essential for Rust programming jobs, especially when building libraries, frameworks, or any code that needs abstraction and polymorphism.
Progress0 / 4 steps