Back to Blog

Rust Traits Tutorial - Define Shared Behavior | Rust for Beginners #25

Sandy LaneSandy Lane

Video: Rust Traits Tutorial - Define Shared Behavior | Rust for Beginners #25 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust Traits Tutorial - Define Shared Behavior

Traits in Rust allow you to define shared behavior that multiple types can implement, enabling polymorphism and code reuse. This tutorial covers how to define traits, implement them for different structs, and provide default method implementations that types can override.

Code

// Define a trait named Summary with a required method summarize
trait Summary {
  fn summarize(&self) -> String;
}

// Define a struct Article with some fields
struct Article {
  headline: String,
  author: String,
  content: String,
}

// Implement the Summary trait for Article
impl Summary for Article {
  fn summarize(&self) -> String {
    format!("{} by {}", self.headline, self.author)
  }
}

// Define another trait Speak with a method speak
trait Speak {
  fn speak(&self) -> &str;
}

// Define two structs Dog and Cat
struct Dog;
struct Cat;

// Implement Speak trait for Dog
impl Speak for Dog {
  fn speak(&self) -> &str {
    "Woof!"
  }
}

// Implement Speak trait for Cat
impl Speak for Cat {
  fn speak(&self) -> &str {
    "Meow!"
  }
}

// Define a trait Greet with a default implementation
trait Greet {
  fn greet(&self) -> &str {
    "Hello"
  }
}

// Struct Formal overrides the default greet method
struct Formal;
impl Greet for Formal {
  fn greet(&self) -> &str {
    "Good day"
  }
}

// Struct Casual uses the default greet method
struct Casual;
impl Greet for Casual {}

fn main() {
  let article = Article {
    headline: String::from("Rust Traits"),
    author: String::from("Celeste"),
    content: String::from("Learn how to use traits in Rust."),
  };
  println!("{}", article.summarize());

  let dog = Dog;
  let cat = Cat;
  println!("Dog says: {}", dog.speak());
  println!("Cat says: {}", cat.speak());

  let formal = Formal;
  let casual = Casual;
  println!("Formal greeting: {}", formal.greet());
  println!("Casual greeting: {}", casual.greet());
}

Key Points

  • Traits define a set of methods that types must implement, acting as contracts.
  • Multiple types can implement the same trait with different behavior for each.
  • Traits can provide default method implementations that types can override or use as-is.
  • Using traits enables polymorphism, allowing code to work with different types through a common interface.