Naked Functions · RPIT · LLD · async fn
Rust 2024 Edition 是 Rust 语言的第四个主要版本
| Edition | 发布时间 | 主要特性 |
|---|---|---|
| 2015 | 2015-05-15 | 语言稳定版 |
| 2018 | 2018-12-06 | 模块系统重构 |
| 2021 | 2021-10-21 | 闭包捕获、数组 IntoIter |
| 2024 | 2024 年末 | RPIT 生命周期、async 增强 |
// Cargo.toml
[package]
name = "my-project"
version = "0.1.0"
edition = "2021" // 改为 "2024"
// 自动迁移
cargo fix --edition
使用 cargo fix --edition 自动迁移代码
RPIT = Return Position Impl Trait
在函数返回值位置使用 impl Trait
// RPIT 示例
fn get_iter(&self) -> impl Iterator<Item = &i32> {
self.data.iter()
}
Rust 2024 改变了 RPIT 的生命周期捕获规则
不自动捕获生命周期
fn foo<'a>(
x: &'a i32
) -> impl Debug {
x // ❌ 错误
}
自动捕获所有生命周期
fn foo<'a>(
x: &'a i32
) -> impl Debug {
x // ✅ 正确
}
Rust 2024 中,RPIT 自动捕获所有泛型参数
// 自动捕获生命周期 'a 和类型 T
fn process<'a, T>(
data: &'a [T]
) -> impl Iterator<Item = &'a T> {
data.iter()
}
使用 + 显式指定捕获的泛型参数
// 只捕获 'a,不捕获 T
fn foo<'a, T: Debug>(
x: &'a T
) -> impl Debug + 'a {
x
}
// 捕获多个生命周期
fn bar<'a, 'b>(
x: &'a i32,
y: &'b i32
) -> impl Debug + 'a + 'b {
(x, y)
}
struct Container<T> {
data: Vec<T>,
}
impl<T> Container<T> {
// Rust 2024: 自动捕获生命周期
fn get_ref(&self) -> impl Debug {
&self.data[0]
}
// 显式指定生命周期
fn get_iter(&self) -> impl Iterator<Item = &T> + '_ {
self.data.iter()
}
}
Naked Functions 是无序言/尾声的裸函数
// 启用特性
#![feature(naked_functions)]
// 声明裸函数
#[naked]
unsafe extern "C" fn my_naked_fn() -> ! {
// 必须使用 asm! 或 noreturn asm
core::arch::asm!(
"mov rax, 42",
"ret",
options(noreturn)
);
}
| 场景 | 说明 |
|---|---|
| 操作系统内核 | 中断处理、上下文切换 |
| 引导程序 | 启动代码 |
| 嵌入式 | 中断向量、硬件交互 |
| 性能优化 | 关键路径优化 |
// 中断处理函数
#[naked]
unsafe extern "x86-interrupt" fn page_fault_handler(
frame: InterruptStackFrame,
) {
core::arch::asm!(
"push rax",
"push rbx",
"call handle_page_fault",
"pop rbx",
"pop rax",
"iretq",
options(noreturn)
);
}
Rust 2024 对 async fn 进行了多项增强
// async 闭包语法
let async_closure = async move |x: i32| {
some_async_work(x).await
};
// 调用
let result = async_closure(42).await;
// async 递归函数
async fn traverse(node: &Node) -> i32 {
let left = async {
match &node.left {
Some(n) => Box::pin(traverse(n)).await,
None => 0,
}
};
// ...
}
// 类型别名中使用 impl Trait
type MyIter<'a> = impl Iterator<Item = &'a str>;
fn get_words(s: &str) -> MyIter<'_> {
s.split_whitespace()
}
// 在 impl 块中使用
impl MyStruct {
type Output<'a> = impl Display;
fn get(&'a self) -> Self::Output<'a> {
&self.value
}
}
// let-else 模式
let Some(value) = option else {
return;
};
// 结合模式匹配
let Ok(data) = parse_input(input) else {
eprintln!("Failed to parse");
return Err(ParseError);
};
// 或模式
match value {
Some(1) | Some(2) => "one or two",
Some(3..=10) => "three to ten",
Some(n @ 11..) => "big number: {n}",
None => "none",
}
// 切片模式匹配
fn process(slice: &[i32]) {
match slice {
[] => "empty",
[single] => "one element",
[first, second] => "two elements",
[first, .., last] => "first and last",
[first, rest @ ..] => "first and rest",
};
}
Rust 2024 编译器进行了多项性能优化
LLD 是 LLVM 的链接器,比传统链接器更快
// Cargo.toml
[profile.release]
linker = "lld"
// 或使用环境变量
RUSTFLAGS="-C linker=lld" cargo build
| 链接器 | 速度 | 兼容性 |
|---|---|---|
| ld | 慢 | 最广 |
| gold | 中等 | Linux |
| lld | 快 | 跨平台 |
// 启用增量编译
[profile.dev]
incremental = true
// 增量编译缓存位置
$CARGO_TARGET_DIR/incremental/
增量编译只重新编译修改的部分
| 场景 | Rust 2021 | Rust 2024 |
|---|---|---|
| 首次编译 | 100% | 95% |
| 增量编译 | 100% | 70% |
| 链接时间 | 100% | 50% |
// 设置并行编译线程数
export CARGO_BUILD_JOBS=8
// 或在 .cargo/config.toml
[build]
jobs = 8
// 新的 Error trait
trait Error: Debug + Display {
fn source(&self) -> Option<&(dyn Error + 'static)> { ... }
fn provide<'a>(&'a self, demand: &mut Demand<'a>) { ... }
}
// 使用 provide 提供额外信息
impl Error for MyError {
fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
demand.provide_value(self.code);
}
}
use std::sync::OnceLock;
static CONFIG: OnceLock<Config> = OnceLock::new();
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
Config::load()
})
}
use std::sync::LazyLock;
static NUMBERS: LazyLock<Vec<i32>> = LazyLock::new(|| {
(1..=100).collect()
});
// 首次访问时初始化
fn main() {
println!("{:?}", *NUMBERS);
}
// 新方法
let iter = vec.iter();
// intersperse - 在元素间插入值
iter.intersperse(&0);
// map_while - 条件映射
iter.map_while(|x| x.checked_mul(2));
// chunk_by - 分组
iter.chunk_by(|x| x / 10);
let slice = &mut [1, 2, 3, 4, 5];
// split_at_mut_checked
if let Some((left, right)) = slice.split_at_mut_checked(2) {
// 安全分割
}
// take_first
if let Some(first) = slice.take_first() {
// 取出第一个元素
}
let s = "hello world";
// split_once
if let Some((first, rest)) = s.split_once(' ') { }
// trim_ascii
let trimmed = s.trim_ascii();
// lines_any
for line in s.lines_any() { }
Rust 2024 推荐使用统一错误处理模式
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let file = fs::read_to_string("data.txt")?;
let parsed: Data = serde_json::from_str(&file)?;
process(parsed)?;
Ok(())
}
// thiserror - 自定义错误
use thiserror::Error;
#[derive(Error, Debug)]
enum MyError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Parse error at {position}")]
Parse { position: usize },
}
// anyhow - 简化错误传播
use anyhow::Result;
fn do_something() -> Result<()> {
Ok(())
}
| 运行时 | 特点 | 适用场景 |
|---|---|---|
| Tokio | 功能全面 | 网络服务 |
| async-std | 标准库风格 | 通用应用 |
| smol | 轻量级 | 嵌入式 |
use tokio::{main, time::{sleep, Duration}};
#[main]
async fn main() -> Result<(), Box<dyn Error>> {
// 并发任务
let handle = tokio::spawn(async {
sleep(Duration::from_secs(1)).await;
"done"
});
let result = handle.await?;
Ok(())
}
use async_std::{task, fs};
#[async_std::main]
async fn main() -> std::io::Result<()> {
let content = fs::read_to_string("file.txt").await?;
println!("{}", content);
Ok(())
}
# 查看版本
rustc --version
cargo --version
# 更新工具链
rustup update
# 切换版本
rustup default stable
rustup default nightly
# 添加组件
rustup component add clippy rustfmt
# 运行 Clippy
cargo clippy
# 自动修复
cargo clippy --fix
# 新增 lint
// - await_holding_lock
// - large_futures
// - mutable_key_type
# 格式化代码
cargo fmt
# 检查格式
cargo fmt -- --check
# rustfmt.toml
max_width = 100
tab_spaces = 4
edition = "2024"
# 1. 更新工具链
rustup update stable
# 2. 修改 Cargo.toml
edition = "2024"
# 3. 自动修复
cargo fix --edition
# 4. 检查警告
cargo check
# 5. 运行测试
cargo test
RPIT 生命周期 · Naked Functions · async 增强 · LLD 链接器
| 特性 | 状态 |
|---|---|
| RPIT 生命周期捕获 | 稳定 |
| Naked Functions | 稳定 |
| async 闭包 | 稳定 |
| LLD 链接器 | 默认 |
Rust 2024 - 更快、更强、更安全