Skip to content

Rust Traits — Defining Shared Behavior with Traits, Trait Bounds, and Derive Macros

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Traits. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust traits define shared behavior with method signatures, default implementations, trait bounds for generics, and derive macros for common traits.

What You'll Learn

  • Trait definition and implementation
  • Default trait methods
  • Trait bounds on generics
  • Derive macros

Why It Matters

Traits enable polymorphism without inheritance. DodaZIP uses traits for compression algorithm abstraction. Firefox uses traits for rendering backends.

Real-World Use

Plugin systems, rendering backends, Serialization, comparison and hashing.

trait Summary {
    fn summarize(&self) -> String;

    fn summarize_author(&self) -> String {
        String::from("(unknown)")
    }
}

struct Article {
    headline: String,
    author: String,
    content: String,
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{} by {}", self.headline, self.author)
    }

    fn summarize_author(&self) -> String {
        format!("@{}", self.author)
    }
}

struct Tweet {
    username: String,
    content: String,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

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

fn notify_generic<T: Summary>(item: &T) {
    println!("Breaking: {}", item.summarize());
}

#[derive(Debug, Clone, PartialEq)]
struct User {
    name: String,
    age: u8,
}

fn main() {
    let article = Article {
        headline: String::from("Rust 2024 Released"),
        author: String::from("Rust Team"),
        content: String::from("..."),
    };

    let tweet = Tweet {
        username: String::from("@rustlang"),
        content: String::from("Hello, world!"),
    };

    notify(&article);
    notify(&tweet);

    let user = User { name: String::from("Alice"), age: 30 };
    println!("{:?}", user);
    println!("{:?}", user.clone());
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro