0PricingLogin
Learn Rust Coding · Lesson

Defining and Implementing Traits

Master traits for defining shared behavior across different types, similar to interfaces in other languages.

What are Traits in Rust?

In Rust, traits are a powerful way to define shared behavior across different types. Think of them like interfaces in other languages.

A trait tells Rust that a particular type has certain functionality. If a type implements a trait, it means that type provides the methods defined by that trait.

  • Traits enable polymorphism: working with different types in a uniform way.
  • They're key to Rust's type system and safe abstractions.

Declaring Your First Trait

You define a trait using the trait keyword. Inside, you list method signatures (names, parameters, return types) that any implementing type must provide.

Let's define a simple Summary trait for items that can be summarized.

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

fn main() {
  // Traits are definitions, not directly executable.
  // We will implement and use them in later scenes!
  println!("Trait 'Summary' defined.");
}

All lessons in this course

  1. Writing Generic Code in Rust
  2. Defining and Implementing Traits
  3. Advanced Trait Usage: Associated Types
← Back to Learn Rust Coding