对比面向对象接口,掌握 Trait Bound 约束、where 从句、默认实现以及为何必须遵循 Orphan Rule 保证生态安全。

1. Trait 的定义与实现

pub trait Summary {
    fn summarize(&self) -> String {
        String::from("(Read more...)") // 默认实现
    }
}

pub struct NewsArticle {
    pub headline: String,
}

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

2. 孤儿规则 (Orphan Rule)

你只能在下列条件之一满足时为某个类型实现某个 Trait:

  1. 该 Trait 定义在当前 Crate 中。
  2. 该类型定义在当前 Crate 中。

这从根源上阻止了第三方库意外覆盖标准库或破坏其他库行为的可能。