mcpField
R
rust-systems-programming

rust-systems-programming

github.com/manutej开发62485 次安装40 周前更新
代码仓库

关于 rust-systems-programming

面向开发内存安全、高性能软件的 Rust 系统编程技能,涵盖所有权、并发、异步编程、不安全代码、FFI 和优化。

主要功能

  1. 01所有权、借用与生命周期
  2. 02线程、消息传递与共享状态
  3. 03异步编程与错误处理
  4. 04不安全代码与 FFI
  5. 05内存安全检查与性能优化

适用场景

  1. 01编写并发网络服务
  2. 02构建命令行或嵌入式软件
  3. 03通过 FFI 将 Rust 代码连接到 C

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/manutej/luxor-claude-marketplace --skill rust-systems-programming

安装后在 Claude Code 中输入/rust-systems-programming确认已加载。

附带文件EXAMPLES.mdREADME.md

详细介绍

Rust 系统编程

这是一项全面的技能,用于使用 Rust 构建高性能、内存安全的系统软件。本技能涵盖所有权、借用、并发、异步编程、不安全代码、FFI 和面向系统级开发的性能优化。

何时使用此技能

在以下情况下使用此技能:

  • 构建无需垃圾回收且需要内存安全的系统软件
  • 使用零成本抽象开发高性能应用
  • 编写可防止数据竞争的并发或并行程序
  • 为 I/O 密集型工作负载(Web 服务器、数据库)创建 async/await 应用
  • 处理底层代码、FFI 或硬件接口
  • 使用更安全的替代方案取代 C/C++ 代码
  • 构建命令行工具、网络服务或嵌入式系统
  • 优化应用中对性能要求极高的部分
  • 创建能在编译时保证内存安全的库
  • 开发性能接近原生的 WebAssembly 模块

核心概念

所有权模型

Rust 的所有权系统是其内存安全保证的基础:

所有权规则:

  1. Rust 中的每个值都只有一个所有者
  2. 所有者超出作用域时,值会被丢弃
  3. 所有权可以转移(移动)给新的所有者

移动语义:

struct MyStruct { s: u32 }

fn main() {
    let mut x = MyStruct{ s: 5u32 };
    let y = x;  // Ownership moved from x to y
    // x.s = 6;  // ERROR: x is no longer valid
    // println!("{}", x.s);  // ERROR: cannot use x after move
}

如果某个类型没有实现 Copy,赋值时会转移所有权,而不是复制。这可以在编译时防止双重释放错误和移动后使用错误。

对于 Copy 类型:

let x = 5;  // i32 implements Copy
let y = x;  // x is copied, not moved
println!("{}", x);  // OK: x is still valid
借用和引用

借用允许临时访问数据,而无需取得所有权:

不可变借用:

fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);  // Borrow s1 immutably

    println!("The length of '{}' is {}.", s1, len);  // s1 still valid
}

fn calculate_length(s: &String) -> usize {
    s.len()  // Can read but not modify
}

可变借用:

Rust 会强制执行独占的可变访问,以防止数据竞争:

fn main() {
    let mut value = 3;
    let borrow = &mut value;  // Mutable borrow
    *borrow += 1;
    println!("{}", borrow);  // 4

    // value is accessible again after borrow ends
}

借用规则:

  • 只能拥有一个可变引用,或任意数量的不可变引用
  • 引用必须始终有效(不能是悬垂指针)
  • 可变借用和不可变借用不能共存

常见的借用错误:

fn main() {
    let mut value = 3;
    // Create a mutable borrow of `value`.
    let borrow = &mut value;
    let _sum = value + 1; // ERROR: cannot use `value` because
                          //        it was mutably borrowed
    println!("{}", borrow);
}
生命周期

生命周期确保引用始终有效:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

'a 生命周期参数告诉编译器,只要两个输入引用都有效,返回的引用就会有效。

共享所有权模式

单线程共享所有权使用 Rc(引用计数):

use std::cell::RefCell;
use std::rc::Rc;

struct MyStruct { s: u32 }

fn main() {
    let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
    let y = x.clone();  // Increment reference count
    x.borrow_mut().s = 6;  // Interior mutability via RefCell
    println!("{}", x.borrow().s);
}

Rc<T> 通过引用计数提供共享所有权。RefCell<T> 支持内部可变性,在运行时而非编译时强制执行借用规则。

线程安全共享使用 Arc(原子引用计数):

use std::sync::Arc;
use std::thread;

struct FancyNum {
    num: u8,
}

fn main() {
    let fancy_ref1 = Arc::new(FancyNum { num: 5 });
    let fancy_ref2 = fancy_ref1.clone();

    let x = thread::spawn(move || {
        // `fancy_ref1` can be moved and has a `'static` lifetime
        println!("child thread: {}", fancy_ref1.num);
    });

    x.join().expect("child thread should finish");
    println!("main thread: {}", fancy_ref2.num);
}

Arc<T> 是 Rc<T> 的线程安全版本,使用原子操作进行引用计数。

使用 Box 在堆上分配
Box<T>

Box<T> 是一种拥有所有权的指针,可在堆上分配 T。适用于:

  • 大小已知的递归类型
  • 不应在栈上复制的大型值
  • 使用动态分派的 Trait 对象

并发模式

线程和消息传递

Rust 通过其所有权系统在编译时防止数据竞争:

use std::thread;
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        tx.send("Hello from thread").unwrap();
    });

    let message = rx.recv().unwrap();
    println!("{}", message);
}
使用 Mutex 共享状态
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

主要并发类型:

  • Mutex<T>:用于共享可变状态的互斥锁
  • RwLock<T>:读写锁,允许多个读取者或一个写入者
  • Arc<T>:用于线程安全共享的原子引用计数
  • mpsc:多生产者、单消费者通道
防止数据竞争

ThreadSanitizer 示例:

static mut A: usize = 0;

fn main() {
    let t = std::thread::spawn(|| {
        unsafe { A += 1 };
    });
    unsafe { A += 1 };

    t.join().unwrap();
}

这段代码存在数据竞争。ThreadSanitizer(通过 RUSTFLAGS=-Zsanitizer=thread 启用)可以检测对静态可变数据的并发访问:

WARNING: ThreadSanitizer: data race (pid=10574)
  Read of size 8 at 0x5632dfe3d030 by thread T1:
  Previous write of size 8 at 0x5632dfe3d030 by main thread:

异步编程

Async/Await 基础

Rust 中的异步编程允许并发处理 I/O,而不阻塞线程:

async fn foo(n: usize) {
    if n > 0 {
        Box::pin(foo(n - 1)).await;
    }
}

递归异步函数需要使用 Box::pin(),以便为 Future 指定已知大小。

异步闭包

使用移动语义的异步闭包:

fn force_fnonce<T: async FnOnce()>(t: T) -> T { t }

let x = String::new();
let c = force_fnonce(async move || {
    println!("{x}");
});

当受限于 AsyncFnOnce 时,闭包会通过移动来捕获变量,以确保所有权正确。

异步闭包借用:

let x = &1i32; // Lifetime '1
let c = async move || {
    println!("{:?}", *x);
    // Even though the closure moves x, we're only capturing *x,
    // so the inner coroutine can reborrow the data for its original lifetime.
};

异步闭包中的可变借用:

let mut x = 1i32;
let c = async || {
    x = 1;
    // The parent borrows `x` mutably.
    // When we call `c()`, we implicitly autoref for `AsyncFnMut::async_call_mut`.
    // The inner coroutine captures with the lifetime of the coroutine-closure.
};
常见异步错误

E0373:异步块捕获生命周期较短的变量:

use std::future::Future;

async fn f() {
    let v = vec![1, 2, 3i32];
    spawn(async { //~ ERROR E0373
        println!("{:?}", v)  // v might go out of scope before async block runs
    });
}

fn spawn<F: Future + Send + 'static>(future: F) {
    unimplemented!()
}

解决方案:将变量移动到异步块中:

spawn(async move {
    println!("{:?}", v)
})

不安全代码与 FFI

何时使用 Unsafe

Rust 的 unsafe 关键字允许执行编译器无法验证的操作:

  1. 解引用原始指针
  2. 调用不安全函数或方法
  3. 访问或修改可变静态变量
  4. 实现不安全 trait
  5. 访问联合体的字段

不安全解引用示例:

macro_rules! unsafe_deref {
    () => {
        *(&() as *const ())
    };
}
使用 Unsafe 保证内存安全

不安全的 Sync 实现:

use std::cell::Cell;

struct NotThreadSafe<T> {
    value: Cell<T>,
}

unsafe impl<T> Sync for NotThreadSafe<T> {}

static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
static B: &'static NotThreadSafe<usize> = &A; // ok!

这是 unsafe 的,因为你必须手动确保线程安全。默认情况下,Cell 不实现 Sync,因此此实现需要谨慎推理。

FFI(外部函数接口)

在 Rust 中调用 C 函数:

use std::mem;

#[link(name = "foo")]
extern "C" {
    fn do_twice(f: unsafe extern "C" fn(i32) -> i32, arg: i32) -> i32;
}

unsafe extern "C" fn add_one(x: i32) -> i32 {
    x + 1
}

unsafe extern "C" fn add_two(x: i64) -> i64 {
    x + 2
}

fn main() {
    let answer = unsafe { do_twice(add_one, 5) };
    println!("The answer is: {}", answer);

    // Type-mismatched call (unsafe):
    println!("With CFI enabled, you should not see the next answer");
    let f: unsafe extern "C" fn(i32) -> i32 = unsafe {
        mem::transmute::<*const u8, unsafe extern "C" fn(i32) -> i32>(add_two as *const u8)
    };
    let next_answer = unsafe { do_twice(f, 5) };
    println!("The next answer is: {}", next_answer);
}

控制流完整性(CFI): 启用 CFI 后,类型不匹配的 transmute 会导致程序终止,从而防止控制流劫持。

用于系统调用的内联汇编:

static UNMAP_BASE: usize;
const MEM_RELEASE: usize;
static VirtualFree: usize;
const OffPtr: usize;
const OffFn: usize;

core::arch::asm!("
    push {free_type}
    push {free_size}
    push {base}

    mov eax, fs:[30h]
    mov eax, [eax+8h]
    add eax, {off_fn}
    mov [eax-{off_fn}+{off_ptr}], eax

    push eax

    jmp {virtual_free}
    ",
    off_ptr = const OffPtr,
    off_fn  = const OffFn,

    free_size = const 0,
    free_type = const MEM_RELEASE,

    virtual_free = sym VirtualFree,

    base = sym UNMAP_BASE,
    options(noreturn),
);

此示例演示了如何使用内联汇编直接调用系统函数,以在 Windows 上释放内存。

错误处理

Result 和 Option 类型

Rust 使用 Result<T, E> 和 Option<T> 进行错误处理:

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("Division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10, 2) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}
? 运算符
fn process_file(path: &str) -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string(path)?;
    Ok(content.to_uppercase())
}

? 运算符会将错误向上传播到调用栈,类似于异常,但会在类型签名中明确体现。

自定义错误类型
use std::fmt;

#[derive(Debug)]
enum AppError {
    IoError(std::io::Error),
    ParseError(std::num::ParseIntError),
    Custom(String),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::IoError(e) => write!(f, "IO error: {}", e),
            AppError::ParseError(e) => write!(f, "Parse error: {}", e),
            AppError::Custom(msg) => write!(f, "Error: {}", msg),
        }
    }
}

impl std::error::Error for AppError {}

内存安全与 Sanitizer

AddressSanitizer

检测栈缓冲区溢出:

fn main() {
    let xs = [0, 1, 2, 3];
    let _y = unsafe { *xs.as_ptr().offset(4) };
}

使用 AddressSanitizer 构建:

$ export RUSTFLAGS=-Zsanitizer=address RUSTDOCFLAGS=-Zsanitizer=address
$ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu

输出:

==37882==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffe400e6250
READ of size 4 at 0x7ffe400e6250 thread T0
    #0 0x5609a841fb1f in example::main::h628ffc6626ed85b2 /.../src/main.rs:3:23

Address 0x7ffe400e6250 is located in stack of thread T0 at offset 48 in frame
  This frame has 1 object(s):
    [32, 48) 'xs' (line 2) <== Memory access at offset 48 overflows this variable

检测堆缓冲区溢出:

fn main() {
    let xs = vec![0, 1, 2, 3];
    let _y = unsafe { *xs.as_ptr().offset(4) };
}

检测作用域结束后使用:

static mut P: *mut usize = std::ptr::null_mut();

fn main() {
    unsafe {
        {
            let mut x = 0;
            P = &mut x;
        }
        std::ptr::write_volatile(P, 123);  // P points to dropped variable
    }
}

AddressSanitizer 输出:

==39249==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7ffc7ed3e1a0
WRITE of size 8 at 0x7ffc7ed3e1a0 thread T0

性能优化

零成本抽象

Rust 提供了不会带来运行时开销的高级抽象:

// Iterator chains are optimized to simple loops
let sum: i32 = (1..100)
    .filter(|x| x % 2 == 0)
    .map(|x| x * x)
    .sum();

编译器会将其优化为紧凑循环,其效果等同于手动迭代。

内联与单态化

泛型函数会针对每种具体类型进行单态化(专门化):

#[inline]
fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
    a + b
}

let x = add(5, 3);      // Specialized for i32
let y = add(5.0, 3.0);  // Specialized for f64
智能指针开销

不同智能指针的开销各不相同:

  • Box<T>:单次堆分配,无额外开销
  • Rc<T>:引用计数,每次克隆或丢弃时有少量开销
  • Arc<T>:原子引用计数,为保证线程安全而带来更高开销
  • Mutex<T>:获取锁的开销
  • RefCell<T>:运行时借用检查的开销
避免分配
// Bad: Allocates a new String
fn greet_bad(name: &str) -> String {
    format!("Hello, {}", name)
}

// Good: Returns a reference, no allocation
fn greet_good(name: &str) -> impl std::fmt::Display + '_ {
    format_args!("Hello, {}", name)
}

常见模式与惯用法

Builder 模式
struct Config {
    host: String,
    port: u16,
    timeout: u64,
}

impl Config {
    fn builder() -> ConfigBuilder {
        ConfigBuilder::default()
    }
}

#[derive(Default)]
struct ConfigBuilder {
    host: Option<String>,
    port: Option<u16>,
    timeout: Option<u64>,
}

impl ConfigBuilder {
    fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    fn build(self) -> Config {
        Config {
            host: self.host.unwrap_or_else(|| "localhost".to_string()),
            port: self.port.unwrap_or(8080),
            timeout: self.timeout.unwrap_or(30),
        }
    }
}
Newtype 模式
struct UserId(u64);
struct PostId(u64);

fn get_user(id: UserId) -> User { /* ... */ }

// This won't compile: type safety!
// get_user(PostId(42));
RAII(资源获取即初始化)
struct FileGuard {
    file: std::fs::File,
}

impl FileGuard {
    fn new(path: &str) -> std::io::Result<Self> {
        Ok(FileGuard {
            file: std::fs::File::create(path)?,
        })
    }
}

impl Drop for FileGuard {
    fn drop(&mut self) {
        println!("File closed automatically");
    }
}

闭包模式与错误

E0500:闭包借用冲突

问题:

fn you_know_nothing(jon_snow: &mut i32) {
    let nights_watch = &jon_snow;
    let starks = || {
        *jon_snow = 3; // error: closure requires unique access to `jon_snow`
                       //        but it is already borrowed
    };
    println!("{}", nights_watch);
}

解决方案:

fn you_know_nothing(jon_snow: &mut i32) {
    let nights_watch = &jon_snow;
    println!("{}", nights_watch);  // Use the borrow first
    // Borrow ends here (non-lexical lifetimes)
    let starks = || {
        *jon_snow = 3;  // Now OK
    };
}
E0502:可变借用与不可变借用

问题:

fn bar(x: &mut i32) {}
fn foo(a: &mut i32) {
    let y = &a;
    bar(a);  // Error: cannot borrow as mutable while borrowed as immutable
    println!("{}", y);
}

解决方案:

fn bar(x: &mut i32) {}
fn foo(a: &mut i32) {
    bar(a);  // Mutable borrow first
    let y = &a; // Immutable borrow after mutable borrow ends
    println!("{}", y);
}
E0505:移动已借用的值

问题:

struct Value {}

fn borrow(val: &Value) {}
fn eat(val: Value) {}

fn main() {
    let x = Value{};
    let _ref_to_val: &Value = &x;
    eat(x);  // Error: cannot move x while borrowed
    borrow(_ref_to_val);
}
E0524:闭包中的并发可变借用

问题:

fn set(x: &mut isize) {
    *x += 4;
}

fn dragoooon(x: &mut isize) {
    let mut c1 = || set(x);
    let mut c2 = || set(x); // error: two closures trying to borrow mutably
    c2();
    c1();
}

解决方案 1:顺序执行(非词法生命周期)

fn set(x: &mut isize) {
    *x += 4;
}

fn dragoooon(x: &mut isize) {
    {
        let mut c1 = || set(&mut *x);
        c1();
    } // `c1` has been dropped here so we're free to use `x` again!
    let mut c2 = || set(&mut *x);
    c2();
}

解决方案 2:使用 Rc + RefCell 共享可变访问

use std::rc::Rc;
use std::cell::RefCell;

fn set(x: &mut isize) {
    *x += 4;
}

fn dragoooon(x: &mut isize) {
    let x = Rc::new(RefCell::new(x));
    let y = Rc::clone(&x);
    let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
    let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); };

    c2();
    c1();
}
E0507:移动已借用的内容

问题:

use std::cell::RefCell;

struct TheDarkKnight;

impl TheDarkKnight {
    fn nothing_is_true(self) {}
}

fn main() {
    let x = RefCell::new(TheDarkKnight);
    x.borrow().nothing_is_true(); // Error: cannot move out of borrowed content
}

解决方案 1:获取引用

impl TheDarkKnight {
    fn nothing_is_true(&self) {}  // Change to &self
}

fn main() {
    let x = RefCell::new(TheDarkKnight);
    x.borrow().nothing_is_true(); // OK
}

解决方案 2:重新获得所有权

fn main() {
    let x = RefCell::new(TheDarkKnight);
    let x = x.into_inner(); // Reclaim ownership
    x.nothing_is_true(); // OK
}

生产环境模式

结构化日志记录
use tracing::{info, warn, error, instrument};

#[instrument]
async fn process_request(id: u64) -> Result<(), Error> {
    info!(request_id = id, "Processing request");

    match do_work(id).await {
        Ok(_) => {
            info!("Request completed successfully");
            Ok(())
        }
        Err(e) => {
            error!(error = ?e, "Request failed");
            Err(e)
        }
    }
}
配置管理
use serde::Deserialize;

#[derive(Deserialize)]
struct AppConfig {
    database_url: String,
    server_port: u16,
    log_level: String,
}

fn load_config() -> Result<AppConfig, config::ConfigError> {
    config::Config::builder()
        .add_source(config::File::with_name("config"))
        .add_source(config::Environment::with_prefix("APP"))
        .build()?
        .try_deserialize()
}
优雅关闭
use tokio::signal;

async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }

    println!("Shutdown signal received, starting graceful shutdown");
}
连接池
use deadpool_postgres::{Config, Pool, Runtime};
use tokio_postgres::NoTls;

async fn create_pool() -> Pool {
    let mut cfg = Config::new();
    cfg.host = Some("localhost".to_string());
    cfg.dbname = Some("mydb".to_string());

    cfg.create_pool(Some(Runtime::Tokio1), NoTls)
        .expect("Failed to create pool")
}

async fn query_user(pool: &Pool, id: i64) -> Result<User, Error> {
    let client = pool.get().await?;
    let row = client
        .query_one("SELECT * FROM users WHERE id = $1", &[&id])
        .await?;
    Ok(User::from_row(row))
}

最佳实践

API 设计
  1. 默认使用引用:除非需要所有权,否则接受 &T,而不是 T
  2. 返回所有权类型:返回 String,而不是 &str,以简化 API
  3. 实现标准 trait:Debug、Clone、PartialEq、Send、Sync
  4. 使用 Into<T> 增强灵活性:fn set_name(&mut self, name: impl Into<String>)
  5. 充分利用类型系统:使用 newtype、枚举和 Result 确保正确性
测试模式
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_addition() {
        assert_eq!(add(2, 2), 4);
    }

    #[test]
    #[should_panic(expected = "division by zero")]
    fn test_divide_by_zero() {
        divide(10, 0);
    }

    #[tokio::test]
    async fn test_async_function() {
        let result = fetch_data().await;
        assert!(result.is_ok());
    }
}
文档
/// Calculates the sum of two numbers.
///
/// # Examples
///
/// ```
/// let result = add(2, 2);
/// assert_eq!(result, 4);
/// ```
///
/// # Panics
///
/// This function will panic if the result overflows.
pub fn add(a: i32, b: i32) -> i32 {
    a.checked_add(b).expect("overflow in add")
}
依赖管理
[dependencies]
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
tracing = "0.1"

[dev-dependencies]
criterion = "0.5"

[profile.release]
lto = true
codegen-units = 1

故障排除

常见的借用检查器问题

问题:"Cannot borrow as mutable because it is also borrowed as immutable" 解决方案:确保可变借用和不可变借用在作用域内不重叠

问题:"Cannot move out of borrowed content" 解决方案:克隆该值、获取引用,或使用 Rc<RefCell<T>>

问题:"Lifetime issues with references" 解决方案:添加显式生命周期标注,或重构代码以避免复杂的生命周期

性能问题

问题:编译时间过长 解决方案:使用增量编译,减少泛型实例化次数,并使用 cargo check

问题:运行时性能低于预期 解决方案:使用 perf 进行性能分析,启用 LTO,并检查是否存在不必要的分配或克隆

问题:内存使用量过高 解决方案:使用引用代替克隆,考虑以流式方式处理数据,并使用 Valgrind 进行性能分析

并发问题

问题:多个互斥锁导致死锁 解决方案:始终按相同顺序获取锁,并使用带超时的 try_lock

问题:不安全代码中的数据竞争 解决方案:使用 ThreadSanitizer 运行,并仔细检查 unsafe 代码块

问题:异步任务无法取得进展 解决方案:检查异步代码中是否存在阻塞操作,并对受 CPU 限制的工作使用 spawn_blocking

快速参考

智能指针速查表
Box<T>     - Heap allocation, single owner
Rc<T>      - Reference counted, single-threaded
Arc<T>     - Atomic reference counted, thread-safe
Mutex<T>   - Mutual exclusion lock
RwLock<T>  - Reader-writer lock
RefCell<T> - Runtime borrow checking
Cell<T>    - Interior mutability for Copy types
常见 trait 实现
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct MyStruct {
    field: String,
}

impl Default for MyStruct {
    fn default() -> Self {
        Self {
            field: String::new(),
        }
    }
}

impl std::fmt::Display for MyStruct {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "MyStruct({})", self.field)
    }
}
异步运行时对比
Tokio:    Full-featured, most popular, excellent ecosystem
async-std: Mirrors std library API, simpler for beginners
smol:     Lightweight, minimal dependencies

资源


技能版本:1.0.0 最后更新:2025 年 10 月 技能类别:系统编程、性能、内存安全 Context7 集成:Rust 文档和错误代码示例

评论

支持 Markdown