Skip to main content
Be Bitwise
RustTraits & Generics

Defining Traits

Traits describe shared behaviour: a method set that any type can sign up to implement. Think interfaces, the Rust dialect.

Basic Trait

rust
trait Summary {
fn summarize(&self) -> String;
}
struct Article {
title: String,
author: String,
content: String,
}
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} by {}", self.title, self.author)
}
}
let article = Article {
title: String::from("Rust 2024"),
author: String::from("Ferris"),
content: String::from("..."),
};
println!("{}", article.summarize());

Default Implementations

Traits can provide default method bodies:

rust
trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
impl Summary for Article {
fn summarize_author(&self) -> String {
self.author.clone()
}
// summarize() uses the default implementation
}
Key Concept

Default implementations let you bolt new methods onto a trait without breaking everyone who already implemented it. That's how Rust's standard library grows: new methods land on existing traits, defaults included, and old code keeps compiling.

Traits as Parameters

rust
fn notify(item: &impl Summary) {
println!("Breaking news: {}", item.summarize());
}

Anything that implements Summary slots straight in.

Multiple Traits

rust
use std::fmt::Display;
fn notify(item: &(impl Summary + Display)) {
println!("{}: {}", item, item.summarize());
}

Common Standard Library Traits

TraitPurposeExample
DisplayUser-facing string formattingformat!("{}", x)
DebugDeveloper-facing formattingformat!("{:?}", x)
CloneExplicit duplicate (the type decides how deep)x.clone()
CopyImplicit copy (stack types)let y = x;
PartialEqEquality comparisonx == y
PartialOrdOrdering comparisonx < y
IteratorIterationfor x in iter
From/IntoType conversionString::from("hello")

Deriving Traits

For the common traits, Rust will write the implementation for you:

rust
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: f64,
y: f64,
}
let p = Point { x: 1.0, y: 2.0 };
println!("{:?}", p); // Debug
let p2 = p.clone(); // Clone
assert_eq!(p, p2); // PartialEq

Version below derives its comparisons and writes Display by hand. Derived ordering compares fields from top to bottom, so the field order matters.

Try itPredict the sorted order (1.10 versus 1.2 trips up string sorting), then move patch above major in the struct and run it again.
Rust (1.40.0)