ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 7 min read

Traits & Generic Programming: Shared Behavior

Defining trait interfaces, impl Trait, and trait bounds

Traits define shared behavior abstractly, functioning like Interfaces in other languages. Generics with Trait Bounds enable high-speed static polymorphism via Monomorphization.

Traits and Trait Bounds

Trait definition: pub trait Summary { fn summarize(&self) -> String; }.

Implementation: impl Summary for NewsArticle { ... }.

Trait Bounds: fn notify<T: Summary>(item: &T) guarantees at compile time that type T implements Summary.

Trait Implementation in Rust
pub trait Describable {
    fn describe(&self) -> String;
}

pub struct Course {
    pub title: String,
    pub lessons: u32,
}

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

pub fn print_item_info<T: Describable>(item: &T) {
    println!("Item: {}", item.describe());
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the Rust equivalent of an Interface in Java or C#?