Member-only story
This article is open to everyone, non-members can access it via this link
Traits are a fundamental concept in Rust that allow you to define shared behaviours across types. They serve as a way to abstract common functionality into a single interface, allowing you to write code that is more generic and reusable.
In this tutorial, we will cover the basics of traits in Rust and provide some concise examples to help you understand how they work.
Defining a Trait
A trait is defined using the trait
keyword, followed by the trait name and a set of method signatures. Here's an example:
trait Printable {
fn print(&self);
}rust
This defines a trait called Printable
with a single method signature, print()
. Any type that implements this trait must provide an implementation for the print()
method.
Implementing a Trait
To implement a trait for a type, you use the impl
keyword followed by the trait name and the type you want to implement it for. Here's an example:
struct Person {
name: String,
age: u8,
}
impl Printable for Person {
fn print(&self) {
println!("Name: {}, Age: {}", self.name, self.age);
}
}