RRust By Example
intermediateTraits

Trait Basic

Define and implement traits for custom types.

Trait Basic

Define and implement traits for custom types.

Difficulty

Intermediate

Code

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

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

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

fn main() {
    let article = Article {
        title: String::from("Rust is Great"),
        author: String::from("Ferris"),
    };
    println!("{}", article.summarize());
}

Explanation

Traits define shared behavior. impl Trait for Type provides implementation.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the traits category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Traits Examples