Member-only story
Traits
In our previous writeup, we looked at Lifetimes and their importance in Rust. If you missed it, you can check it out below.
In Rust, a trait is a way to define a set of methods that types can implement. Think of it as a blueprint for behavior.
If you’ve worked in other languages, traits are somewhat akin to interfaces in Java or protocols in Swift, but Rust’s traits have their own unique flavor, blending flexibility with the language’s strict safety guarantees.
Imagine you’re building a notification system for a web app. You need to send alerts via email, SMS, or push notifications. Each method of delivery is different, but they all share a common goal: delivering a message. A trait lets you define a send method that all these delivery methods must have, while allowing each to handle the specifics in its own way.
trait Notifier {
fn send(&self, message: &str) -> Result<(), String>;
}Here, the Notifier trait declares a send method that takes a message and returns a Result to indicate success or failure. Any type that wants to be a Notifier must implement this…

