Traits Basics
8 examples to get you started with traits - 5 basic and 3 intermediate.
Busca en todas las páginas de la documentación
8 examples to get you started with traits - 5 basic and 3 intermediate.
trait Greet {
fn greet(&self) -> String;
}
struct Person { name: String }
impl Greet for Person {
fn greet(&self) -> String {
format!("Hello, {}!", self.name)
}
}
fn main() {
let p = Person { name: "Ada".into() };
println!("{}", p.greet());
}impl Trait for Type provides implementationtrait Log {
fn level(&self) -> &'static str { "info" }
fn msg(&self) -> &str;
}
struct Event(&'static str);
impl Log for Event {
fn msg(&self) -> &str { self.0 }
}use std::fmt::Display;
fn print_twice<T: Display>(value: T) {
println!("{value} {value}");
}
fn main() {
print_twice(42);
}T: Display constrains generic parameterT+impl Trait in Parametersuse std::fmt::Display;
fn show(value: impl Display) {
println!("{value}");
}impl Display ~= T: Display anonymous+ for multiple: impl Display + Cloneimpl Traitfn make_greeting() -> impl std::fmt::Display {
"hello"
}
fn main() {
println!("{}", make_greeting());
}dyn Trait trait objectsdyn Traittrait Drawable { fn draw(&self); }
struct Circle;
impl Drawable for Circle { fn draw(&self) { println!("circle"); } }
fn render(shape: &dyn Drawable) {
shape.draw();
}
fn main() {
render(&Circle);
}trait Outline: std::fmt::Display {
fn outline(&self) -> String;
}Outline: Display requires Display firstimpl Outline must also impl Displaytrait Iter {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Iterator::Item is canonical exampleRelated: Traits & Generics Best Practices
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026