Day 16: Traits
MediumTraitsPolymorphismimpl Trait

Day 16: Traits

Traits define shared behavior that types can implement - similar to interfaces in other languages.

Defining a Trait

trait Summary {
    fn summarize(&self) -> String;
    
    // Default implementation
    fn preview(&self) -> String {
        format!("Read more: {}", self.summarize())
    }
}

Implementing a Trait

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

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{}: {}", self.title, &self.content[..50])
    }
}

Traits as Parameters

// impl Trait syntax (simpler)
fn notify(item: &impl Summary) {
    println!("Breaking: {}", item.summarize());
}

// Trait bound syntax (more flexible)
fn notify<T: Summary>(item: &T) {
    println!("Breaking: {}", item.summarize());
}

Common traits in Rust: Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default

The Task

  1. Define a Describable trait with a describe(&self) -> String method
  2. Implement it for Dog (return "Dog: {name}")
  3. Implement it for Cat (return "Cat: {name}")

Requirements

  • Both structs have a name: String field
  • Trait method returns a String
  • Test only uses Dog { name: "Buddy" }

Hints

trait Describable {
    fn describe(&self) -> String;
}

impl Describable for Dog {
    fn describe(&self) -> String {
        format!("Dog: {}", self.name)
    }
}
Language: Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Output
Run to see the result here.
    Day 16: Traits · RUST Challenge | learn.sol