Skip to content

默认实现

> 掌握 Trait 默认实现的语法和用法,学会继承和覆盖默认行为。

默认实现

概念名称: Trait 方法可以提供默认实现,实现者可以选择覆盖或继承。

语法结构:
┌──────────────────────────────────────┐
│  trait Trait名 {                      │
│      fn 方法名(&self) -> 返回类型 {   │
│          默认实现代码                  │
│      }                                │
│  }                                    │
│                                       │
│  impl Trait名 for 类型 {}            │
│  → 继承默认实现                        │
│                                       │
│  impl Trait名 for 类型 {              │
│      fn 方法名(&self) -> 返回类型 {   │
│          自定义实现                    │
│      }                                │
│  }                                    │
│  → 覆盖默认实现                        │
└──────────────────────────────────────┘

最简示例

rust
trait Greet {
    fn greet(&self) -> String {
        "Hello!".to_string()
    }
}

struct Person;
impl Greet for Person {}

fn main() {
    let p = Person;
    println!("{}", p.greet());  // Hello!
}
▶ Run

详细示例

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

pub struct Tweet {
    pub username: String,
    pub content: String,
}

// 可以使用默认实现
impl Summary for Tweet {}

pub struct NewsArticle {
    pub headline: String,
    pub author: String,
}

// 重写默认实现
impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {}", self.headline, self.author)
    }
}

fn main() {
    let tweet = Tweet {
        username: String::from("user"),
        content: String::from("content"),
    };

    let article = NewsArticle {
        headline: String::from("Breaking News"),
        author: String::from("John"),
    };

    // Tweet 使用默认实现
    println!("Tweet: {}", tweet.summarize());  // (Read more...)
    
    // NewsArticle 使用自定义实现
    println!("Article: {}", article.summarize());  // Breaking News, by John
}
▶ Run

关键代码说明:

代码含义为什么这样写
fn summarize(&self) -> String { ... }默认实现提供合理的默认行为
impl Summary for Tweet {}空实现块继承默认实现,无需额外代码
fn summarize(&self) -> String { format!(...) }覆盖实现针对特定类型定制行为

小结

  • Trait 方法可以提供默认实现,减少重复代码
  • 空实现块 impl Trait for Type {} 继承所有默认方法
  • 可以选择性覆盖默认实现,定制特定类型的行为
  • 默认实现可以调用其他 Trait 方法,提供组合能力
  • 默认实现是 Trait 设计的重要技巧

练习题

详见:练习题