Day 3:特徵(Traits)

學習目標

  • 定義 trait 與預設方法
  • 實作 trait 於不同型別
  • 用 trait 讓不同型別共用行為

今日重點

定義 trait

trait Summary {
    fn summarize(&self) -> String;   // 需要實作

    // 預設實作,可被覆寫
    fn preview(&self) -> String {
        format!("{}...", &self.summarize()[..50])
    }
}

為不同型別實作

struct NewsArticle { headline: String, author: String }
impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {}", self.headline, self.author)
    }
}

struct Tweet { username: String, content: String }
impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

為什麼重要?

trait 定義一組**不同型別都有的行為**。你在做「策略模式」「多型」時,Rust 用 trait(而非繼承)達成。

練習

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

struct Dog { name: String }
struct Cat { name: String }

impl Describe for Dog {
    fn describe(&self) -> String { format!("{} 是一隻狗", self.name) }
}
impl Describe for Cat {
    fn describe(&self) -> String { format!("{} 是一隻貓", self.name) }
}
1. 定義 Describe trait 並為 Dog / Cat 實作。 2. 給 trait 加一個 make_sound(&self) -> String 的預設實作。

自我檢查

  • 能定義 trait
  • 能為不同型別實作 trait
  • 知道預設實作與覆寫
  • 理解 trait 是 Rust 達成「多型」的方式

深入連結

  • The Book 第 10 章「Defining a Trait」