读音与词义
prelude 的读音:英式/美式均为 /ˈprel.juːd/("prel-yood")
含义 :名词,意为"序曲、前奏、序幕"。在编程语言中,指自动导入的预定义模块,为代码提供开箱即用的常用功能。
详细说明
自动导入
在 Rust 2024 版本中,每个模块都会自动导入:
rust
use std::prelude::rust_2024::*;
这意味着你可以直接使用 prelude 中定义的类型、trait 和函数,无需显式导入。
Prelude 包含的内容
std::prelude 主要包含:
常见类型:
String,Vec,Option,ResultBox,Cow,Slice
重要 trait:
| 类别 | trait |
|---|---|
| 转换相关 | AsRef, AsMut, Into, From |
| 标记 trait | Send, Sync, Sized |
| 内存与复制 | Clone, Copy, Drop |
| 格式化与默认 | Default, Debug |
| 闭包 | Fn, FnMut, FnOnce |
| 迭代器 | Iterator, DoubleEndedIterator, ExactSizeIterator |
| 异步 (2024 新增) | Future, IntoFuture |
常用宏:
println!,format!,vec!,assert!等
示例对比
rust
// 不需要这样写:
// use std::option::Option;
// use std::vec::Vec;
// use std::string::String;
// use std::boxed::Box;
// use std::future::Future; // 2024 版本中也不需要显式导入
fn main() {
// 可以直接使用,因为已经在 prelude 中
let v: Vec<i32> = vec![1, 2, 3];
let s = String::from("hello");
let o: Option<i32> = Some(42);
let b = Box::new(5);
println!("{}", s);
}
禁用 Prelude
如果需要避免自动导入(例如在 no_std 环境中),可以使用 #![no_implicit_prelude] 属性:
rust
#![no_implicit_prelude]
// 现在必须显式导入所有内容
extern crate std;
use std::prelude::rust_2024::*;
各版本对应关系
| Rust 版本 | 默认导入的 prelude |
|---|---|
| Rust 2015 | std::prelude::v1 |
| Rust 2018 | std::prelude::rust_2018 |
| Rust 2021 | std::prelude::rust_2021 |
| Rust 2024 | std::prelude::rust_2024 |
2024 版本特别说明
Rust 2024 Edition 在 prelude 中新增了 Future 和 IntoFuture 两个异步 trait,这意味着异步编程时无需显式导入这些核心 trait。
升级注意事项 :由于 Future 被加入 prelude,如果代码中存在与 poll 方法同名的方法,可能会产生歧义。运行以下命令可自动修复:
bash
cargo fix --edition
注意
- 在
no_std环境中,只有core::prelude会被导入 - 不同 Rust Edition 的 prelude 内容可能略有差异,2024 版本是最新标准