rust-patterns by affaan-m/everything-claude-code
npx skills add https://github.com/affaan-m/everything-claude-code --skill rust-patterns构建安全、高性能、可维护应用程序的惯用 Rust 模式和最佳实践。
此技能在六个关键领域强制执行惯用的 Rust 约定:所有权和借用以在编译时防止数据竞争,库使用 thiserror、应用程序使用 anyhow 的 Result/? 错误传播,枚举和穷尽模式匹配使非法状态无法表示,零成本抽象的 trait 和泛型,通过 Arc<Mutex<T>>、通道和 async/await 实现的安全并发,以及按领域组织的最小化 pub 公开接口。
Rust 的所有权系统在编译时防止数据竞争和内存错误。
// 良好:不需要所有权时传递引用
fn process(data: &[u8]) -> usize {
data.len()
}
// 良好:仅在需要存储或消费时获取所有权
fn store(data: Vec<u8>) -> Record {
Record { payload: data }
}
// 不良:为避免借用检查器而进行不必要的克隆
fn process_bad(data: &Vec<u8>) -> usize {
let cloned = data.clone(); // 浪费资源——直接借用即可
cloned.len()
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
Cow 实现灵活的所有权use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input) // 无需修改时零成本
}
}
Result 和 ? —— 生产环境绝不使用 unwrap()// 良好:附带上下文传播错误
use anyhow::{Context, Result};
fn load_config(path: &str) -> Result<Config> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read config from {path}"))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("failed to parse config from {path}"))?;
Ok(config)
}
// 不良:出错时 panic
fn load_config_bad(path: &str) -> Config {
let content = std::fs::read_to_string(path).unwrap(); // Panic!
toml::from_str(&content).unwrap()
}
thiserror,应用程序错误使用 anyhow// 库代码:结构化、类型化的错误
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StorageError {
#[error("record not found: {id}")]
NotFound { id: String },
#[error("connection failed")]
Connection(#[from] std::io::Error),
#[error("invalid data: {0}")]
InvalidData(String),
}
// 应用程序代码:灵活的错误处理
use anyhow::{bail, Result};
fn run() -> Result<()> {
let config = load_config("app.toml")?;
if config.workers == 0 {
bail!("worker count must be > 0");
}
Ok(())
}
Option 组合子而非嵌套匹配// 良好:组合子链
fn find_user_email(users: &[User], id: u64) -> Option<String> {
users.iter()
.find(|u| u.id == id)
.map(|u| u.email.clone())
}
// 不良:深层嵌套匹配
fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
match users.iter().find(|u| u.id == id) {
Some(user) => match &user.email {
email => Some(email.clone()),
},
None => None,
}
}
// 良好:不可能的状态无法表示
enum ConnectionState {
Disconnected,
Connecting { attempt: u32 },
Connected { session_id: String },
Failed { reason: String, retries: u32 },
}
fn handle(state: &ConnectionState) {
match state {
ConnectionState::Disconnected => connect(),
ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
ConnectionState::Connecting { .. } => wait(),
ConnectionState::Connected { session_id } => use_session(session_id),
ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
ConnectionState::Failed { reason, .. } => log_failure(reason),
}
}
// 良好:显式处理每个变体
match command {
Command::Start => start_service(),
Command::Stop => stop_service(),
Command::Restart => restart_service(),
// 添加新变体会强制在此处处理
}
// 不良:通配符隐藏新变体
match command {
Command::Start => start_service(),
_ => {} // 静默忽略 Stop、Restart 及未来变体
}
// 良好:泛型输入,具体输出
fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
Ok(buf)
}
// 良好:多个约束的 trait 边界
fn process<T: Display + Send + 'static>(item: T) -> String {
format!("processed: {item}")
}
// 需要异构集合或插件系统时使用
trait Handler: Send + Sync {
fn handle(&self, request: &Request) -> Response;
}
struct Router {
handlers: Vec<Box<dyn Handler>>,
}
// 需要性能时使用泛型(单态化)
fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response {
handler.handle(request)
}
// 良好:不同的类型防止参数混淆
struct UserId(u64);
struct OrderId(u64);
fn get_order(user: UserId, order: OrderId) -> Result<Order> {
// 不会意外交换用户 ID 和订单 ID
todo!()
}
// 不良:容易交换参数
fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> {
todo!()
}
struct ServerConfig {
host: String,
port: u16,
max_connections: usize,
}
impl ServerConfig {
fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {
ServerConfigBuilder { host: host.into(), port, max_connections: 100 }
}
}
struct ServerConfigBuilder { host: String, port: u16, max_connections: usize }
impl ServerConfigBuilder {
fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }
fn build(self) -> ServerConfig {
ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }
}
}
// 用法:ServerConfig::builder("localhost", 8080).max_connections(200).build()
// 良好:声明式、惰性、可组合
let active_emails: Vec<String> = users.iter()
.filter(|u| u.is_active)
.map(|u| u.email.clone())
.collect();
// 不良:命令式累积
let mut active_emails = Vec::new();
for user in &users {
if user.is_active {
active_emails.push(user.email.clone());
}
}
collect()// 收集到不同类型
let names: Vec<_> = items.iter().map(|i| &i.name).collect();
let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect();
let combined: String = parts.iter().copied().collect();
// 收集 Result —— 在第一个错误处短路
let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
Arc<Mutex<T>>use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..10).map(|_| {
let counter = Arc::clone(&counter);
std::thread::spawn(move || {
let mut num = counter.lock().expect("mutex poisoned");
*num += 1;
})
}).collect();
for handle in handles {
handle.join().expect("worker thread panicked");
}
use std::sync::mpsc;
let (tx, rx) = mpsc::sync_channel(16); // 带背压的有界通道
for i in 0..5 {
let tx = tx.clone();
std::thread::spawn(move || {
tx.send(format!("message {i}")).expect("receiver disconnected");
});
}
drop(tx); // 关闭发送方,使 rx 迭代器终止
for msg in rx {
println!("{msg}");
}
use tokio::time::Duration;
async fn fetch_with_timeout(url: &str) -> Result<String> {
let response = tokio::time::timeout(
Duration::from_secs(5),
reqwest::get(url),
)
.await
.context("request timed out")?
.context("request failed")?;
response.text().await.context("failed to read body")
}
// 生成并发任务
async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> {
let handles: Vec<_> = urls.into_iter()
.map(|url| tokio::spawn(async move {
fetch_with_timeout(&url).await
}))
.collect();
let mut results = Vec::with_capacity(handles.len());
for handle in handles {
results.push(handle.await.unwrap_or_else(|e| panic!("spawned task panicked: {e}")));
}
results
}
// 可接受:有文档记录不变量的 FFI 边界(Rust 2024+)
/// # Safety
/// `ptr` must be a valid, aligned pointer to an initialized `Widget`.
unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
// SAFETY: caller guarantees ptr is valid and aligned
unsafe { &*ptr }
}
// 可接受:有正确性证明的性能关键路径
// SAFETY: index is always < len due to the loop bound
unsafe { slice.get_unchecked(index) }
// 不良:使用 unsafe 绕过借用检查器
// 不良:为方便而使用 unsafe
// 不良:没有 Safety 注释就使用 unsafe
// 不良:在不相关类型之间进行转换
my_app/
├── src/
│ ├── main.rs
│ ├── lib.rs
│ ├── auth/ # 领域模块
│ │ ├── mod.rs
│ │ ├── token.rs
│ │ └── middleware.rs
│ ├── orders/ # 领域模块
│ │ ├── mod.rs
│ │ ├── model.rs
│ │ └── service.rs
│ └── db/ # 基础设施
│ ├── mod.rs
│ └── pool.rs
├── tests/ # 集成测试
├── benches/ # 基准测试
└── Cargo.toml
// 良好:内部共享使用 pub(crate)
pub(crate) fn validate_input(input: &str) -> bool {
!input.is_empty()
}
// 良好:从 lib.rs 重新导出公共 API
pub mod auth;
pub use auth::AuthMiddleware;
// 不良:将所有内容都设为 pub
pub fn internal_helper() {} // 应设为 pub(crate) 或私有
# 构建和检查
cargo build
cargo check # 无需代码生成的快速类型检查
cargo clippy # 代码检查和建议
cargo fmt # 格式化代码
# 测试
cargo test
cargo test -- --nocapture # 显示 println 输出
cargo test --lib # 仅单元测试
cargo test --test integration # 仅集成测试
# 依赖项
cargo audit # 安全审计
cargo tree # 依赖树
cargo update # 更新依赖项
# 性能
cargo bench # 运行基准测试
| 惯用法 | 描述 |
|---|---|
| 借用,而非克隆 | 传递 &T 而非克隆,除非需要所有权 |
| 使非法状态无法表示 | 使用枚举仅对有效状态建模 |
使用 ? 而非 unwrap() | 传播错误,库/生产代码绝不 panic |
| 解析,而非验证 | 在边界将非结构化数据转换为类型化结构体 |
| 新类型确保类型安全 | 包装基本类型以防止参数交换 |
| 优先使用迭代器而非循环 | 声明式链更清晰且通常更快 |
在 Result 上使用 #[must_use] | 确保调用者处理返回值 |
使用 Cow 实现灵活所有权 | 借用足够时避免分配 |
| 穷尽匹配 | 业务关键枚举不使用通配符 _ |
最小化 pub 公开接口 | 内部 API 使用 pub(crate) |
// 不良:生产代码中使用 .unwrap()
let value = map.get("key").unwrap();
// 不良:为满足借用检查器而 .clone(),却不理解原因
let data = expensive_data.clone();
process(&original, &data);
// 不良:`&str` 足够时使用 String
fn greet(name: String) { /* should be &str */ }
// 不良:库中使用 Box<dyn Error>(应改用 thiserror)
fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() }
// 不良:忽略 must_use 警告
let _ = validate(input); // 静默丢弃 Result
// 不良:在 async 上下文中阻塞
async fn bad_async() {
std::thread::sleep(Duration::from_secs(1)); // 阻塞执行器!
// 应使用:tokio::time::sleep(Duration::from_secs(1)).await;
}
请记住:如果代码能编译,它很可能是正确的——但前提是避免使用 unwrap()、最小化 unsafe 使用,并让类型系统为你工作。
每周安装量
376
代码仓库
GitHub 星标数
105.0K
首次出现
9 天前
安全审计
安装于
codex359
cursor321
opencode320
gemini-cli318
github-copilot318
amp318
Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
This skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, Result/? error propagation with thiserror for libraries and anyhow for applications, enums and exhaustive pattern matching to make illegal states unrepresentable, traits and generics for zero-cost abstraction, safe concurrency via Arc<Mutex<T>>, channels, and async/await, and minimal pub surfaces organized by domain.
Rust's ownership system prevents data races and memory bugs at compile time.
// Good: Pass references when you don't need ownership
fn process(data: &[u8]) -> usize {
data.len()
}
// Good: Take ownership only when you need to store or consume
fn store(data: Vec<u8>) -> Record {
Record { payload: data }
}
// Bad: Cloning unnecessarily to avoid borrow checker
fn process_bad(data: &Vec<u8>) -> usize {
let cloned = data.clone(); // Wasteful — just borrow
cloned.len()
}
Cow for Flexible Ownershipuse std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input) // Zero-cost when no mutation needed
}
}
Result and ? — Never unwrap() in Production// Good: Propagate errors with context
use anyhow::{Context, Result};
fn load_config(path: &str) -> Result<Config> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("failed to read config from {path}"))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("failed to parse config from {path}"))?;
Ok(config)
}
// Bad: Panics on error
fn load_config_bad(path: &str) -> Config {
let content = std::fs::read_to_string(path).unwrap(); // Panics!
toml::from_str(&content).unwrap()
}
thiserror, Application Errors with anyhow// Library code: structured, typed errors
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StorageError {
#[error("record not found: {id}")]
NotFound { id: String },
#[error("connection failed")]
Connection(#[from] std::io::Error),
#[error("invalid data: {0}")]
InvalidData(String),
}
// Application code: flexible error handling
use anyhow::{bail, Result};
fn run() -> Result<()> {
let config = load_config("app.toml")?;
if config.workers == 0 {
bail!("worker count must be > 0");
}
Ok(())
}
Option Combinators Over Nested Matching// Good: Combinator chain
fn find_user_email(users: &[User], id: u64) -> Option<String> {
users.iter()
.find(|u| u.id == id)
.map(|u| u.email.clone())
}
// Bad: Deeply nested matching
fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
match users.iter().find(|u| u.id == id) {
Some(user) => match &user.email {
email => Some(email.clone()),
},
None => None,
}
}
// Good: Impossible states are unrepresentable
enum ConnectionState {
Disconnected,
Connecting { attempt: u32 },
Connected { session_id: String },
Failed { reason: String, retries: u32 },
}
fn handle(state: &ConnectionState) {
match state {
ConnectionState::Disconnected => connect(),
ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
ConnectionState::Connecting { .. } => wait(),
ConnectionState::Connected { session_id } => use_session(session_id),
ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
ConnectionState::Failed { reason, .. } => log_failure(reason),
}
}
// Good: Handle every variant explicitly
match command {
Command::Start => start_service(),
Command::Stop => stop_service(),
Command::Restart => restart_service(),
// Adding a new variant forces handling here
}
// Bad: Wildcard hides new variants
match command {
Command::Start => start_service(),
_ => {} // Silently ignores Stop, Restart, and future variants
}
// Good: Generic input, concrete output
fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::new();
reader.read_to_end(&mut buf)?;
Ok(buf)
}
// Good: Trait bounds for multiple constraints
fn process<T: Display + Send + 'static>(item: T) -> String {
format!("processed: {item}")
}
// Use when you need heterogeneous collections or plugin systems
trait Handler: Send + Sync {
fn handle(&self, request: &Request) -> Response;
}
struct Router {
handlers: Vec<Box<dyn Handler>>,
}
// Use generics when you need performance (monomorphization)
fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response {
handler.handle(request)
}
// Good: Distinct types prevent mixing up arguments
struct UserId(u64);
struct OrderId(u64);
fn get_order(user: UserId, order: OrderId) -> Result<Order> {
// Can't accidentally swap user and order IDs
todo!()
}
// Bad: Easy to swap arguments
fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> {
todo!()
}
struct ServerConfig {
host: String,
port: u16,
max_connections: usize,
}
impl ServerConfig {
fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {
ServerConfigBuilder { host: host.into(), port, max_connections: 100 }
}
}
struct ServerConfigBuilder { host: String, port: u16, max_connections: usize }
impl ServerConfigBuilder {
fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }
fn build(self) -> ServerConfig {
ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }
}
}
// Usage: ServerConfig::builder("localhost", 8080).max_connections(200).build()
// Good: Declarative, lazy, composable
let active_emails: Vec<String> = users.iter()
.filter(|u| u.is_active)
.map(|u| u.email.clone())
.collect();
// Bad: Imperative accumulation
let mut active_emails = Vec::new();
for user in &users {
if user.is_active {
active_emails.push(user.email.clone());
}
}
collect() with Type Annotation// Collect into different types
let names: Vec<_> = items.iter().map(|i| &i.name).collect();
let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect();
let combined: String = parts.iter().copied().collect();
// Collect Results — short-circuits on first error
let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
Arc<Mutex<T>> for Shared Mutable Stateuse std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..10).map(|_| {
let counter = Arc::clone(&counter);
std::thread::spawn(move || {
let mut num = counter.lock().expect("mutex poisoned");
*num += 1;
})
}).collect();
for handle in handles {
handle.join().expect("worker thread panicked");
}
use std::sync::mpsc;
let (tx, rx) = mpsc::sync_channel(16); // Bounded channel with backpressure
for i in 0..5 {
let tx = tx.clone();
std::thread::spawn(move || {
tx.send(format!("message {i}")).expect("receiver disconnected");
});
}
drop(tx); // Close sender so rx iterator terminates
for msg in rx {
println!("{msg}");
}
use tokio::time::Duration;
async fn fetch_with_timeout(url: &str) -> Result<String> {
let response = tokio::time::timeout(
Duration::from_secs(5),
reqwest::get(url),
)
.await
.context("request timed out")?
.context("request failed")?;
response.text().await.context("failed to read body")
}
// Spawn concurrent tasks
async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> {
let handles: Vec<_> = urls.into_iter()
.map(|url| tokio::spawn(async move {
fetch_with_timeout(&url).await
}))
.collect();
let mut results = Vec::with_capacity(handles.len());
for handle in handles {
results.push(handle.await.unwrap_or_else(|e| panic!("spawned task panicked: {e}")));
}
results
}
// Acceptable: FFI boundary with documented invariants (Rust 2024+)
/// # Safety
/// `ptr` must be a valid, aligned pointer to an initialized `Widget`.
unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
// SAFETY: caller guarantees ptr is valid and aligned
unsafe { &*ptr }
}
// Acceptable: Performance-critical path with proof of correctness
// SAFETY: index is always < len due to the loop bound
unsafe { slice.get_unchecked(index) }
// Bad: Using unsafe to bypass borrow checker
// Bad: Using unsafe for convenience
// Bad: Using unsafe without a Safety comment
// Bad: Transmuting between unrelated types
my_app/
├── src/
│ ├── main.rs
│ ├── lib.rs
│ ├── auth/ # Domain module
│ │ ├── mod.rs
│ │ ├── token.rs
│ │ └── middleware.rs
│ ├── orders/ # Domain module
│ │ ├── mod.rs
│ │ ├── model.rs
│ │ └── service.rs
│ └── db/ # Infrastructure
│ ├── mod.rs
│ └── pool.rs
├── tests/ # Integration tests
├── benches/ # Benchmarks
└── Cargo.toml
// Good: pub(crate) for internal sharing
pub(crate) fn validate_input(input: &str) -> bool {
!input.is_empty()
}
// Good: Re-export public API from lib.rs
pub mod auth;
pub use auth::AuthMiddleware;
// Bad: Making everything pub
pub fn internal_helper() {} // Should be pub(crate) or private
# Build and check
cargo build
cargo check # Fast type checking without codegen
cargo clippy # Lints and suggestions
cargo fmt # Format code
# Testing
cargo test
cargo test -- --nocapture # Show println output
cargo test --lib # Unit tests only
cargo test --test integration # Integration tests only
# Dependencies
cargo audit # Security audit
cargo tree # Dependency tree
cargo update # Update dependencies
# Performance
cargo bench # Run benchmarks
| Idiom | Description |
|---|---|
| Borrow, don't clone | Pass &T instead of cloning unless ownership is needed |
| Make illegal states unrepresentable | Use enums to model valid states only |
? over unwrap() | Propagate errors, never panic in library/production code |
| Parse, don't validate | Convert unstructured data to typed structs at the boundary |
| Newtype for type safety | Wrap primitives in newtypes to prevent argument swaps |
| Prefer iterators over loops | Declarative chains are clearer and often faster |
#[must_use] on Results | Ensure callers handle return values |
| for flexible ownership |
// Bad: .unwrap() in production code
let value = map.get("key").unwrap();
// Bad: .clone() to satisfy borrow checker without understanding why
let data = expensive_data.clone();
process(&original, &data);
// Bad: Using String when &str suffices
fn greet(name: String) { /* should be &str */ }
// Bad: Box<dyn Error> in libraries (use thiserror instead)
fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() }
// Bad: Ignoring must_use warnings
let _ = validate(input); // Silently discarding a Result
// Bad: Blocking in async context
async fn bad_async() {
std::thread::sleep(Duration::from_secs(1)); // Blocks the executor!
// Use: tokio::time::sleep(Duration::from_secs(1)).await;
}
Remember : If it compiles, it's probably correct — but only if you avoid unwrap(), minimize unsafe, and let the type system work for you.
Weekly Installs
376
Repository
GitHub Stars
105.0K
First Seen
9 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex359
cursor321
opencode320
gemini-cli318
github-copilot318
amp318
Android 整洁架构指南:模块化设计、依赖注入与数据层实现
902 周安装
Cow| Avoid allocations when borrowing suffices |
| Exhaustive matching | No wildcard _ for business-critical enums |
Minimal pub surface | Use pub(crate) for internal APIs |