0
0
Rustprogramming~30 mins

Defining traits in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the AnimalSound trait
Define a trait called AnimalSound with a method make_sound that returns a &str.
Rust
Hint

Use the trait keyword to define a trait. The method make_sound should take &self and return a string slice &str.

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

Define structs with no fields using struct Dog; and struct Cat;.

3
Implement AnimalSound 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 define the method to return the correct sound string.

4
Create instances and print their sounds
In the main function, create a Dog and a Cat. Then print their sounds by calling make_sound on each.
Rust
Hint

Create variables dog and cat as instances of Dog and Cat. Use println! to print their sounds.