0
0
Rustprogramming~20 mins

Why traits are used in Rust - See It in Action

Choose your learning style9 modes available
Why traits are used
📖 Scenario: Imagine you are building a program that handles different types of animals. Each animal can make a sound, but the way they make sounds is different. You want a way to tell your program that all animals can make a sound, without writing the same code for each animal.
🎯 Goal: You will create a trait called AnimalSound that defines a behavior for making a sound. Then, you will implement this trait for different animal types. Finally, you will call the sound method on each animal to see their unique sounds.
📋 What You'll Learn
Create a trait called AnimalSound with a method make_sound
Create two structs: Dog and Cat
Implement the AnimalSound trait for both Dog and Cat
Call the make_sound method for both animals and print the results
💡 Why This Matters
🌍 Real World
Traits are used in Rust to define common behaviors for different types, like animals making sounds or shapes calculating area.
💼 Career
Understanding traits is essential for Rust programming jobs, as they enable writing clean, modular, and maintainable code.
Progress0 / 4 steps
1
Create the structs for animals
Create two structs called Dog and Cat with no fields.
Rust
Hint

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

2
Create the trait AnimalSound
Create a trait called AnimalSound with a method make_sound that returns a &str.
Rust
Hint

Define the trait with trait AnimalSound { fn make_sound(&self) -> &str; }.

3
Implement the trait for Dog and Cat
Implement the AnimalSound trait for Dog and Cat. For Dog, make_sound should return "Bark". For Cat, it should return "Meow".
Rust
Hint

Use impl AnimalSound for Dog and impl AnimalSound for Cat with the method returning the correct sounds.

4
Call the make_sound method and print results
Create instances of Dog and Cat. Call their make_sound methods and print the results using println!.
Rust
Hint

Create dog and cat variables, then print their sounds with println!("Dog says: {}", dog.make_sound()).