Learn more: The Rust Reference, The Book, Rust by Example, Rust Design Patterns
In Rust, a trait is a way to define shared behavior that can be implemented by multiple types. Traits are similar to interfaces in other languages but with some unique features specific to Rust. Here’s a high-level overview of traits in Rust:
Shared Behavior: Traits allow you to define methods that different types can share.
Type Safety: Traits ensure that only types that provide implementations for the trait’s methods can use the behavior defined by the trait. This promotes type safety and helps prevent errors at compile time.
Abstract Definition: When you define a trait, you’re creating an abstract definition of functionality without specifying how it’s done. The actual implementation of the methods is provided by the types that implement the trait.
Trait Bounds: You can use traits to specify that a generic type can be any type that has certain behavior, known as trait bounds. This allows for more flexible and reusable code1.
Associated Types: Traits can also define associated types, which are types that are associated with the trait and are used within the trait’s method signatures. Implementors of the trait will specify the concrete type to be used.
Default method implementations.
Here’s a simple example of a trait in Rust:
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
headline: String,
location: String,
author: String,
content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
struct Tweet {
username: String,
content: String,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}