4 多态

多态 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/idiomatic/polymorphism.html

4 多态

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
pub trait Trait {}

pub struct HasGeneric<T>(T);

pub enum Either<A, B> {
    Left(A),
    Right(B),
}

fn takes_generic<T: Trait>(value: &T) {}

fn takes_dyn(value: &dyn Trait) {}
  • Rust 提供了丰富的多态机制,但与其它流行语言的做法有所不同!

  • 本章将介绍 Rust 多态的细节,以及它与其它语言的异同。


4.1 要点回顾

要点回顾 — Comprehensive Rust

4.2 从 OOP 到 Rust

从 OOP 到 Rust — Comprehensive Rust

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