🦀 Rust 最新特性

2026 年度更新

Rust 2024 Edition & 新特性解析

Naked Functions · RPIT · LLD · async fn

📅 Rust 2024 Edition

Rust 2024 Edition 是 Rust 语言的第四个主要版本

Edition发布时间主要特性
20152015-05-15语言稳定版
20182018-12-06模块系统重构
20212021-10-21闭包捕获、数组 IntoIter
20242024 年末RPIT 生命周期、async 增强

🔄 Edition 迁移

// Cargo.toml
[package]
name = "my-project"
version = "0.1.0"
edition = "2021"  // 改为 "2024"

// 自动迁移
cargo fix --edition

使用 cargo fix --edition 自动迁移代码

📋 Edition 变更概览

  • ✅ RPIT 生命周期捕获规则变更
  • ✅ async fn 增强
  • ✅ 闭包语法改进
  • ✅ 模块路径解析变更
  • ✅ 预lude 新增 trait

🎯 RPIT 概述

RPIT = Return Position Impl Trait

在函数返回值位置使用 impl Trait

// RPIT 示例
fn get_iter(&self) -> impl Iterator<Item = &i32> {
    self.data.iter()
}

🔄 RPIT 生命周期

Rust 2024 改变了 RPIT 的生命周期捕获规则

Rust 2021

不自动捕获生命周期

fn foo<'a>(
    x: &'a i32
) -> impl Debug {
    x  // ❌ 错误
}

Rust 2024

自动捕获所有生命周期

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

Naked Functions 是无序言/尾声的裸函数

  • 不生成函数序言(prologue)
  • 不生成函数尾声(epilogue)
  • 完全控制汇编代码
  • 适用于操作系统开发、嵌入式

⚙️ 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 Functions 示例

// 中断处理函数
#[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)
    );
}

⚡ async fn 增强

Rust 2024 对 async fn 进行了多项增强

  • async 闭包稳定
  • async 递归支持
  • async 生命周期改进
  • async fn in traits

🔒 async 闭包

// async 闭包语法
let async_closure = async move |x: i32| {
    some_async_work(x).await
};

// 调用
let result = async_closure(42).await;

🔄 async 递归

// async 递归函数
async fn traverse(node: &Node) -> i32 {
    let left = async {
        match &node.left {
            Some(n) => Box::pin(traverse(n)).await,
            None => 0,
        }
    };
    // ...
}

📊 类型系统增强

  • ✅ 类型别名中的 impl Trait
  • ✅ let-else 模式稳定
  • ✅ 切片模式增强
  • ✅ 泛型关联类型改进

🎯 impl Trait 增强

// 类型别名中使用 impl Trait
type MyIter<'a> = impl Iterator<Item = &'a str>;

fn get_words(s: &str) -> MyIter<'_> {
    s.split_whitespace()
}

📝 类型别名 impl

// 在 impl 块中使用
impl MyStruct {
    type Output<'a> = impl Display;
    
    fn get(&'a self) -> Self::Output<'a> {
        &self.value
    }
}

✅ let-else 模式

// 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 链接器默认启用
  • 增量编译改进
  • 并行编译优化
  • 编译缓存优化

🔗 LLD 链接器

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 2021Rust 2024
首次编译100%95%
增量编译100%70%
链接时间100%50%

🔄 并行编译

// 设置并行编译线程数
export CARGO_BUILD_JOBS=8

// 或在 .cargo/config.toml
[build]
jobs = 8

📦 标准库更新

  • ✅ Error trait 改进
  • ✅ OnceLock / LazyLock
  • ✅ 迭代器新方法
  • ✅ 切片和字符串增强

❌ Error trait

// 新的 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);
    }
}

🔒 OnceLock

use std::sync::OnceLock;

static CONFIG: OnceLock<Config> = OnceLock::new();

fn get_config() -> &'static Config {
    CONFIG.get_or_init(|| {
        Config::load()
    })
}

🔄 LazyLock

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(())
}

📦 anyhow / thiserror

// 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轻量级嵌入式

🚀 Tokio 更新

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(())
}

🌊 async-std

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(())
}

🌿 生态系统

  • 🔗 Serde - 序列化
  • 🌐 Axum / Actix - Web 框架
  • 💾 SQLx / Diesel - 数据库
  • 📊 Tracing - 日志追踪
  • 🧪 Proptest - 属性测试

🔧 工具链

# 查看版本
rustc --version
cargo --version

# 更新工具链
rustup update

# 切换版本
rustup default stable
rustup default nightly

# 添加组件
rustup component add clippy rustfmt

🔍 Clippy 增强

# 运行 Clippy
cargo clippy

# 自动修复
cargo clippy --fix

# 新增 lint
// - await_holding_lock
// - large_futures
// - mutable_key_type

📝 rustfmt

# 格式化代码
cargo fmt

# 检查格式
cargo fmt -- --check

# rustfmt.toml
max_width = 100
tab_spaces = 4
edition = "2024"

💡 最佳实践

  • ✅ 使用 clippy 检查代码
  • ✅ 使用 rustfmt 格式化
  • ✅ 编写单元测试和集成测试
  • ✅ 使用 文档注释
  • ✅ 处理所有错误,避免 unwrap

📋 迁移指南

# 1. 更新工具链
rustup update stable

# 2. 修改 Cargo.toml
edition = "2024"

# 3. 自动修复
cargo fix --edition

# 4. 检查警告
cargo check

# 5. 运行测试
cargo test

📝 总结

Rust 2024 主要更新

RPIT 生命周期 · Naked Functions · async 增强 · LLD 链接器

特性状态
RPIT 生命周期捕获稳定
Naked Functions稳定
async 闭包稳定
LLD 链接器默认

🎯 关键特性

  • 🔄 RPIT 自动捕获生命周期
  • 🔧 Naked Functions 裸函数支持
  • async fn 增强
  • 🔗 LLD 链接器加速
  • 📦 LazyLock 延迟初始化
  • let-else 模式稳定

🔮 未来展望

  • 🎯 async fn in traits 完整支持
  • 🎯 泛型关联类型完善
  • 🎯 const generics 增强
  • 🎯 编译器性能持续优化
  • 🎯 更多标准库 API

📚 参考资料

  • 🔗 Rust 官网: rust-lang.org
  • 🔗 Edition Guide: doc.rust-lang.org/edition-guide
  • 🔗 Rust Blog: blog.rust-lang.org
  • 🔗 RFCs: github.com/rust-lang/rfcs

🦀 Happy Rustaceaning!

Rust 2024 - 更快、更强、更安全