Lesson 13

Traits and Generics

Write flexible code that works with different types.

Learning objectives

Traits

A trait defines shared behavior. Types can implement a trait to provide specific behavior while following a common interface.

Generics

Generics allow you to write code that works with multiple types instead of one fixed type.

Trait Bounds

Trait bounds tell Rust what behavior a generic type must support.

Example code

trait Describable {
    fn describe(&self) -> String;
}

struct Course {
    title: String,
}

impl Describable for Course {
    fn describe(&self) -> String {
        format!("Course: {}", self.title)
    }
}

fn print_description<T: Describable>(item: T) {
    println!("{}", item.describe());
}

fn main() {
    let course = Course {
        title: String::from("Rust Made Easy"),
    };
    print_description(course);
}
Practice task: Create a trait called Printable and implement it for a struct named Invoice.