4.2.10 异构集合
10-异构集合 — Comprehensive Rust
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/idiomatic/polymorphism/from-oop-to-rust/dynamic-dispatch/heterogeneous.html
4.2.10 异构集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| // Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
use std::fmt::Display;
pub struct Lambda;
impl Display for Lambda {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "λ")
}
}
fn main() {
let heterogeneous: Vec<Box<dyn Display>> = vec![
Box::new(42u32),
Box::new(String::from("Woah")),
Box::new(Lambda),
];
for item in heterogeneous {
// 我们知道 "item" 实现了 Display,但别的一无所知!
println!("Display output: {}", item);
}
}
|