0
0
Rustprogramming~3 mins

Why Implementing traits in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could teach many different things to do the same action without rewriting it every time?

The Scenario

Imagine you have many different types of vehicles, like cars, bikes, and boats, and you want each to have a way to start. Without a shared plan, you must write separate start methods for each type manually.

The Problem

Writing separate start methods for every vehicle type is slow and error-prone. If you want to add a new vehicle, you must remember to add its start method everywhere. This leads to repeated code and confusion.

The Solution

Implementing traits lets you define a shared behavior blueprint. You write the start method once as a trait, then each vehicle type implements it. This keeps code organized, reusable, and easy to extend.

Before vs After
Before
struct Car; impl Car { fn start(&self) { println!("Car started"); } } struct Bike; impl Bike { fn start(&self) { println!("Bike started"); } }
After
trait Start { fn start(&self); } struct Car; impl Start for Car { fn start(&self) { println!("Car started"); } } struct Bike; impl Start for Bike { fn start(&self) { println!("Bike started"); } }
What It Enables

It enables writing flexible and consistent code where different types share common behaviors without repeating yourself.

Real Life Example

In a game, you can define a trait for all characters to attack. Each character type implements the attack differently, but the game calls the same attack method on all.

Key Takeaways

Manual methods for each type cause repeated code and mistakes.

Traits provide a shared behavior blueprint to implement across types.

This makes code cleaner, reusable, and easier to maintain.