</>
Skip to content
Rust lessons (28/43)

Rust — Traits

Basic trait

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

struct Article {
    title: String,
    content: String,
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{}: {}", self.title, &self.content[..50])
    }
}

Default implementations

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

    fn preview(&self) -> String {
        format!("{}...", &self.summarize()[..20])
    }
}

Traits as parameters

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

// Trait bound syntax
fn notify2<T: Summary>(item: &T) {
    println!("Breaking: {}", item.summarize());
}

// Multiple traits
fn display(item: &(impl Summary + std::fmt::Display)) {
    println!("{}", item);
}

Return traits

fn create_summarizable() -> impl Summary {
    Article {
        title: String::from("News"),
        content: String::from("Something important happened today..."),
    }
}

Trait bounds

use std::fmt::Display;

fn longest_with_announcement<'a, T: Display>(
    x: &'a str,
    y: &'a str,
    ann: T,
) -> &'a str {
    println!("Announcement: {}", ann);
    if x.len() > y.len() { x } else { y }
}

Derive traits

#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}

fn main() {
    let p1 = Point { x: 1.0, y: 2.0 };
    let p2 = p1.clone();
    println!("{:?}", p1);
    println!("Equal: {}", p1 == p2);
}

Mini Practice

Write Rust code that:

  1. Defines a trait with a method
  2. Implements the trait for a struct
  3. Uses trait bounds in a function
  4. Derives common traits

Up Next

In the next lesson, you'll learn about Generics — writing reusable code.

Related Topics

Frequently Asked Questions about Traits

What is Traits in Rust?

Traits is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Traits?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Traits.

Why is Traits important in Rust?

Traits is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.