0PricingLogin
Learn Rust Coding · Lesson

Defining Traits

Shared behavior.

What Is a Trait?

A trait defines shared behavior — a set of methods a type can implement. It is similar to an interface in other languages.

Traits let different types agree on a common contract.

Declaring a Trait

Use the trait keyword followed by method signatures. The signatures declare what implementors must provide.

trait Greet {
    fn hello(&self) -> String;
}

fn main() {
    println!("trait declared");
}

All lessons in this course

  1. Defining Traits
  2. Trait Objects and dyn
  3. Static vs Dynamic Dispatch
  4. Default Methods
← Back to Learn Rust Coding