返回顶部
r

rust-patternsRust模式集

Production Rust patterns covering ownership, async Tokio, Axum web framework, SQLx, error handling, CLI tools, WASM, and PyO3 Python bindings

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
572
下载量
免费
免费
0
收藏
概述
安装方式
版本历史

rust-patterns

Rust系统编程模式

描述

一份面向2026年的生产级Rust模式综合指南。涵盖所有权与借用心智模型、使用thiserror/anyhow的错误处理、基于Tokio的异步并发、基于Axum的Web服务、数据库访问(SQLx、Diesel、SeaORM)、CLI开发、WebAssembly以及通过PyO3实现的Python绑定。目标Rust版本为2024版(1.85.0+)。

使用方法

安装此技能可获得生产级Rust模式,包括:

  • - 所有权、借用和生命周期规则的具体心智模型
  • 针对库与应用程序的thiserror vs anyhow选择指南
  • Tokio运行时模式:spawn、select!、streams
  • Axum Web服务器:路由、提取器、中间件、共享状态
  • 并发原语:Arc、Mutex、RwLock、通道、Rayon

在Rust项目中使用时,此技能为以下场景提供上下文:

  • - 决定何时使用clone、borrow或move
  • 组织异步代码以避免阻塞事件循环
  • 根据项目需求选择数据库库
  • 使用Clap v4派生API构建CLI工具
  • 使用PyO3创建Python扩展模块

关键模式

所有权心智模型

将所有权视为产权契约:

  • - 移动(let y = x):你转移了契约。x不再有效。
  • 不可变借用(&T):多个读取者同时存在,不可修改。
  • 可变借用(&mut T):一个独占的借用者可以修改。不允许其他借用者。

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 vs anyhow

库代码使用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(())
}

Tokio异步模式

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。

Axum Web服务器

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, 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::>>().pariter().sum();

对于消息传递模式,优先使用通道而非Arc

SQLx:编译时检查的SQL

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。

Clap v4 CLI(派生API)

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 },
}

PyO3:Python绑定

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) -> f64 {
data.iter().sum()
}
// 构建命令:maturin develop --release
// 在Python中使用:import mymodule; result = mymodule.fast_compute([1.0, 2.0])

Rust 2024版

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>>
单一所有者+可变引用,或通道 | | 在库代码中使用.unwrap() | 返回Result | | 在异步函数中使用同步I/O | 使用tokio::fs、spawn_blocking |

工具与参考


MidOS发布 — MCP社区库

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 rust-patterns-1776210052 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 rust-patterns-1776210052 技能

通过命令行安装

skillhub install rust-patterns-1776210052

下载

⬇ 下载 rust-patterns v1.0.0(免费)

文件大小: 3.74 KB | 发布时间: 2026-4-15 12:26

v1.0.0 最新 2026-4-15 12:26
- Initial release of the "rust-patterns" skill.
- Comprehensive guide covering Rust ownership, error handling, async with Tokio, Axum web framework, SQLx, CLI development, WebAssembly, and PyO3 Python bindings.
- Includes production-ready patterns, anti-patterns, and concise code examples for Rust Edition 2024.
- Helpful for structuring async code, error selection (thiserror vs anyhow), database access, concurrency, and building Rust-based tools and Python extensions.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部