What if you could teach many different things to do the same action without rewriting it every time?
Why Implementing traits in Rust? - Purpose & Use Cases
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.
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.
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.
struct Car; impl Car { fn start(&self) { println!("Car started"); } } struct Bike; impl Bike { fn start(&self) { println!("Bike started"); } }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"); } }It enables writing flexible and consistent code where different types share common behaviors without repeating yourself.
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.
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.