Traits are Rust's superpower for abstraction. This chapter explores advanced trait patterns that enable powerful, flexible, and type-safe designs.
While generics use static dispatch (monomorphization), trait objects enable dynamic dispatch when you need runtime polymorphism:
trait Drawable {
fn draw(&self);
}
struct Circle {
radius: f64,
}
struct Rectangle {
width: f64,
height: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing circle with radius {}", self.radius);
}
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing rectangle {}x{}", self.width, self.height);
}
}
// Static dispatch: monomorphized at compile time
fn draw_static<T: Drawable>(item: &T) {
item.draw();
}
// Dynamic dispatch: runtime polymorphism
fn draw_dynamic(item: &dyn Drawable) {
item.draw();
}
fn main() {
let shapes: Vec<Box<dyn Drawable>> = vec![
Box::new(Circle { radius: 5.0 }),
Box::new(Rectangle { width: 10.0, height: 20.0 }),
];
for shape in shapes {
shape.draw();
}
}
<T: Trait>): Faster (inlined), larger binary, known at compile time&dyn Trait): Smaller binary, slight overhead, heterogeneous collectionsNot all traits can be made into trait objects. A trait is object-safe if:
// Object-safe trait
trait Display {
fn display(&self);
}
// NOT object-safe: has generic method
trait NotObjectSafe {
fn generic<T>(&self, value: T); // ❌
}
// NOT object-safe: returns Self
trait AlsoNotObjectSafe {
fn clone_self(&self) -> Self; // ❌
}
// Object-safe version
trait ObjectSafeClone {
fn clone_box(&self) -> Box<dyn ObjectSafeClone>;
}
impl<T> ObjectSafeClone for T
where
T: Clone + 'static,
{
fn clone_box(&self) -> Box<dyn ObjectSafeClone> {
Box::new(self.clone())
}
}
use std::fmt::{Debug, Display};
// Multiple bounds inline
fn print_info<T: Debug + Display + Clone>(item: T) {
println!("Debug: {:?}", item);
println!("Display: {}", item);
let copy = item.clone();
}
// Better: use where clause for readability
fn better_print_info<T>(item: T)
where
T: Debug + Display + Clone,
{
println!("Debug: {:?}", item);
println!("Display: {}", item);
}
// Complex bounds with associated types
fn process<T, U>(iter: T)
where
T: Iterator<Item = U>,
U: Display + Clone,
{
for item in iter {
println!("{}", item);
}
}
use std::fmt;
struct Pair<T> {
first: T,
second: T,
}
// Always implement this
impl<T> Pair<T> {
fn new(first: T, second: T) -> Self {
Pair { first, second }
}
}
// Only implement for types that support comparison
impl<T: PartialOrd> Pair<T> {
fn largest(&self) -> &T {
if self.first >= self.second {
&self.first
} else {
&self.second
}
}
}
// Blanket implementation: implement for all T that implement Display
impl<T: fmt::Display> fmt::Display for Pair<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.first, self.second)
}
}
Rust allows operator overloading through trait implementation:
use std::ops::{Add, Mul, Neg};
#[derive(Debug, Clone, Copy)]
struct Vector2D {
x: f64,
y: f64,
}
impl Add for Vector2D {
type Output = Self;
fn add(self, other: Self) -> Self {
Vector2D {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Mul<f64> for Vector2D {
type Output = Self;
fn mul(self, scalar: f64) -> Self {
Vector2D {
x: self.x * scalar,
y: self.y * scalar,
}
}
}
impl Neg for Vector2D {
type Output = Self;
fn neg(self) -> Self {
Vector2D {
x: -self.x,
y: -self.y,
}
}
}
fn main() {
let v1 = Vector2D { x: 1.0, y: 2.0 };
let v2 = Vector2D { x: 3.0, y: 4.0 };
let v3 = v1 + v2; // Add
let v4 = v1 * 2.0; // Mul
let v5 = -v1; // Neg
println!("{:?}", v3);
}
use std::ops::{Index, IndexMut};
struct Grid<T> {
data: Vec<T>,
width: usize,
height: usize,
}
impl<T> Index<(usize, usize)> for Grid<T> {
type Output = T;
fn index(&self, (x, y): (usize, usize)) -> &T {
&self.data[y * self.width + x]
}
}
impl<T> IndexMut<(usize, usize)> for Grid<T> {
fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut T {
&mut self.data[y * self.width + x]
}
}
fn main() {
let mut grid = Grid {
data: vec![0; 9],
width: 3,
height: 3,
};
grid[(1, 1)] = 5;
println!("{}", grid[(1, 1)]);
}
A trait can require implementors to also implement another trait:
use std::fmt;
// OutlinePrint requires Display
trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
impl OutlinePrint for Point {}
fn main() {
let p = Point { x: 1, y: 2 };
p.outline_print();
}
trait Summary {
fn summarize_author(&self) -> String;
// Default implementation
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
struct Tweet {
username: String,
content: String,
}
impl Summary for Tweet {
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
// Can override default
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
struct Article {
author: String,
headline: String,
}
impl Summary for Article {
fn summarize_author(&self) -> String {
self.author.clone()
}
// Uses default implementation
}
Add methods to existing types without modifying them:
// Extend Iterator with custom methods
trait IteratorExt: Iterator {
fn my_sum(self) -> Self::Item
where
Self: Sized,
Self::Item: std::ops::Add<Output = Self::Item> + Default,
{
self.fold(Self::Item::default(), |acc, x| acc + x)
}
fn my_collect_vec(self) -> Vec<Self::Item>
where
Self: Sized,
{
let mut vec = Vec::new();
for item in self {
vec.push(item);
}
vec
}
}
// Blanket implementation for all iterators
impl<T: Iterator> IteratorExt for T {}
fn main() {
let sum = (1..=5).my_sum();
println!("Sum: {}", sum);
let vec = (1..=5).my_collect_vec();
println!("{:?}", vec);
}
Traits with no methods that mark types with special properties:
// Define a marker trait
trait Trusted {}
struct SafeData;
struct UntrustedData;
impl Trusted for SafeData {}
// Generic function that requires Trusted
fn process_trusted<T: Trusted>(data: T) {
println!("Processing trusted data");
}
fn main() {
let safe = SafeData;
process_trusted(safe); // OK
let unsafe_data = UntrustedData;
// process_trusted(unsafe_data); // ERROR: not Trusted
}
// Standard library examples:
// - Send: type can be transferred across thread boundaries
// - Sync: type can be referenced from multiple threads
// - Copy: bitwise copy is safe
// - Sized: size known at compile time
While async fn in traits is stabilizing, here's how to use them today:
use async_trait::async_trait;
#[async_trait]
trait AsyncDatabase {
async fn query(&self, sql: &str) -> Result<Vec<String>, String>;
async fn execute(&mut self, sql: &str) -> Result<(), String>;
}
struct PostgresDB {
connection: String,
}
#[async_trait]
impl AsyncDatabase for PostgresDB {
async fn query(&self, sql: &str) -> Result<Vec<String>, String> {
// Simulate async query
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
Ok(vec![format!("Result from: {}", sql)])
}
async fn execute(&mut self, sql: &str) -> Result<(), String> {
println!("Executing: {}", sql);
Ok(())
}
}
#[tokio::main]
async fn main() {
let db = PostgresDB {
connection: "localhost".to_string(),
};
let results = db.query("SELECT * FROM users").await.unwrap();
println!("{:?}", results);
}
Common traits can be automatically derived:
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct User {
id: u64,
name: String,
email: String,
}
// Custom derive with derive_more crate
use derive_more::{Add, Display, From};
#[derive(Debug, Add, Display, From)]
struct Money(u64);
fn main() {
let m1 = Money(100);
let m2 = Money(50);
let total = m1 + m2;
println!("{}", total); // Display
}
dyn TraitKorea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.
Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.
Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.