Traits Intro
Define and implement a trait
A trait lists method signatures. Types opt in with impl Trait for Type.
trait Greet {
fn greet(&self) -> String;
}
struct Person { name: String }
impl Greet for Person {
fn greet(&self) -> String {
format!("Hi, {}", self.name)
}
}
Use trait bounds
Generic functions can require that T implements a trait.
fn print_greet<T: Greet>(value: &T) {
println!("{}", value.greet());
}
Common standard traits
Debugfor formatting with{:?}Clonefor explicit copiesDisplayfor user-facing textFrom/Intofor conversions
Derive when possible
Many traits can be auto-implemented.
#[derive(Debug, Clone)]
struct Point { x: i32, y: i32 }
Comments
One comment per signed-in account. Comments are saved with this page’s URL.