类型别名与抽象类型
学习目标
- 掌握
type别名 - 理解
impl Trait在返回位置 - 掌握
type简化复杂类型
核心概念
类型别名
type Kilometers = i32;
type Thunk = Box<dyn Fn() + Send + 'static>;
fn main() {
let distance: Kilometers = 5;
let f: Thunk = Box::new(|| println!("hello"));
}
简化复杂类型
use std::collections::HashMap;
type Cache = HashMap<String, Vec<u8>>;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn process() -> Result<()> {
Ok(())
}
impl Trait 在返回位置
fn make_adder(x: i32) -> impl Fn(i32) -> i32 {
move |y| x + y
}
// 编译器知道具体类型但对外隐藏
不能用 impl Trait 的情况
// ❌ 不能在不同分支返回不同类型
fn make_thing(choice: bool) -> impl std::fmt::Display {
if choice {
42
} else {
"hello" // 类型不同
}
}
// ✅ 用 trait 对象
fn make_thing(choice: bool) -> Box<dyn std::fmt::Display> {
if choice {
Box::new(42)
} else {
Box::new("hello")
}
}
小结
| 语法 | 用途 |
|---|---|
type A = B | 类型别名 |
impl Trait 返回值 | 隐藏具体类型 |
Box<dyn Trait> | 运行时多态 |
练习编辑器
rust
Loading...