3.2 Traits(特征)

Traits(特征)— Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/methods-and-traits/traits.html

3.2 Traits(特征)

Rust 允许用 trait 对类型做抽象。它们类似于接口:

1
2
3
4
5
6
7
8
9
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
trait Pet {
    /// 返回这只宠物说的一句话。
    fn talk(&self) -> String;

    /// 向终端打印一句问候这只宠物的话。
    fn greet(&self);
}
  • Trait 定义了类型要实现该 trait 所必须具备的一组方法。

  • 下一节「泛型」中,我们会看到如何编写对所有实现某 trait 的类型通用的功能。


3.2.1 实现 Trait

01-实现 Trait — Comprehensive Rust

3.2.2 父 Trait

02-父 Trait — Comprehensive Rust

3.2.3 关联类型

03-关联类型 — Comprehensive Rust

最后修改 August 11, 2026: 更新 (70a5af133)