Production Rust patterns covering ownership, async Tokio, Axum web framework, SQLx, error handling, CLI tools, WASM, and PyO3 Python bindings
一份面向2026年的生产级Rust模式综合指南。涵盖所有权与借用心智模型、使用thiserror/anyhow的错误处理、基于Tokio的异步并发、基于Axum的Web服务、数据库访问(SQLx、Diesel、SeaORM)、CLI开发、WebAssembly以及通过PyO3实现的Python绑定。目标Rust版本为2024版(1.85.0+)。
安装此技能可获得生产级Rust模式,包括:
在Rust项目中使用时,此技能为以下场景提供上下文:
将所有权视为产权契约:
rust
// 快速模式参考
fn risky() -> Result
let x = operation()?; // ?运算符:出错时提前返回
Ok(x)
}
// 跨线程共享可变状态
let data = Arc::new(Mutex::new(vec![]));
let clone = Arc::clone(&data);
tokio::spawn(async move { clone.lock().unwrap().push(1); });
库代码使用thiserror(调用者需要可匹配的错误变体):
rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum MyError {
#[error(文件未找到: {0})]
FileNotFound(String),
#[error(IO错误: {0})]
IoError(#[from] io::Error), // 自动从io::Error转换
}
应用程序使用anyhow(为错误链添加上下文):
rust
use anyhow::{Result, Context};
fn main() -> Result<()> {
let data = std::fs::readtostring(user.json)
.context(无法读取user.json)?;
Ok(())
}
rust
// 多线程运行时
#[tokio::main(flavor = multithread, workerthreads = 4)]
async fn main() { ... }
// 竞争Future:select!选择最先完成的
let winner = tokio::select! {
result = slow_future() => result,
result = fast_future() => result,
= tokio::time::sleep(Duration::fromsecs(5)) => 超时,
};
// 异步中的阻塞代码:使用spawn_blocking
let data = tokio::task::spawn_blocking(|| {
std::fs::readtostring(file.txt)
}).await.unwrap();
反模式:在async fn内部进行阻塞同步I/O。应使用tokio::fs代替std::fs。
rust
use axum::{Router, routing::{get, post}, Json, http::StatusCode};
use std::sync::Arc;
#[derive(Clone)]
struct AppState { db_url: String }
async fn create_user(Json(user): Json
(StatusCode::CREATED, Json(user))
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState { db_url: postgres://....into() });
let app = Router::new()
.route(/users, post(create_user))
.with_state(state);
let listener = tokio::net::TcpListener::bind(0.0.0.0:3000).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
rust
// Arc
let counter = Arc::new(Mutex::new(0));
for _ in 0..10 {
let c = Arc::clone(&counter);
thread::spawn(move || { *c.lock().unwrap() += 1; });
}
// RwLock:多个读取者或一个写入者
let data = Arc::new(RwLock::new(vec![a, b]));
let read = data.read().unwrap(); // 共享读取
let write = data.write().unwrap(); // 独占写入
// Rayon:并行迭代器(自动工作窃取)
use rayon::prelude::*;
let sum: u64 = (1..=1000000).collect::
对于消息传递模式,优先使用通道而非Arc
rust
use sqlx::PgPool;
let pool = PgPool::connect(postgres://user:pass@localhost/db).await?;
let users: Vec<(i32, String)> = sqlx::query_as(
SELECT id, name FROM users WHERE age > $1
).bind(18).fetch_all(&pool).await?;
数据库选择:sqlx用于带编译时检查的原始SQL,diesel用于类型安全的查询构建器(同步),sea-orm用于完整的异步ORM。
rust
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = myapp, about = 我的CLI工具)]
struct Cli {
#[arg(short, long)] verbose: bool,
#[command(subcommand)] command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Process { #[arg(short, long)] format: String },
Download { url: String },
}
rust
use pyo3::prelude::*;
#[pymodule]
fn mymodule(py: Python, m: &PyModule) -> PyResult<()> {
m.addfunction(wrappyfunction!(fast_compute, m)?)?;
Ok(())
}
#[pyfunction]
fn fast_compute(data: Vec
data.iter().sum()
}
// 构建命令:maturin develop --release
// 在Python中使用:import mymodule; result = mymodule.fast_compute([1.0, 2.0])
rust
// 异步trait原生支持(无需async_trait crate)
pub trait Fetcher {
async fn fetch(&self, url: &str) -> Result
}
// Let链:更简洁的嵌套条件
if let Some(x) = get_value()
&& x > 0
&& let y = x * 2
&& y < 100
{
println!(所有条件满足: {}, y);
}
| 反模式 | 更好的方法 |
|---|---|
| 过度克隆以绕过借用检查器 | 使用引用&T |
| 到处使用Arc<Mutex<T>> |
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 rust-patterns-1776210052 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 rust-patterns-1776210052 技能
skillhub install rust-patterns-1776210052
文件大小: 3.74 KB | 发布时间: 2026-4-15 12:26