rust-patterns

Solid

地道的Rust模式、所有权、错误处理、特质、并发,以及构建安全、高性能应用程序的最佳实践。

AI & Automation 196,640 stars 30253 forks Updated 2 days ago MIT

Install

View on GitHub

Quality Score: 95/100

Stars 20%
100
Recency 20%
100
Frontmatter 20%
70
Documentation 15%
100
Issue Health 10%
50
License 10%
100
Description 5%
100

Skill Content

# Rust 开发模式 构建安全、高性能且可维护应用程序的惯用 Rust 模式和最佳实践。 ## 何时使用 * 编写新的 Rust 代码时 * 评审 Rust 代码时 * 重构现有 Rust 代码时 * 设计 crate 结构和模块布局时 ## 工作原理 此技能在六个关键领域强制执行惯用的 Rust 约定:所有权和借用,用于在编译时防止数据竞争;`Result`/`?` 错误传播,库使用 `thiserror` 而应用程序使用 `anyhow`;枚举和穷尽模式匹配,使非法状态无法表示;用于零成本抽象的 trait 和泛型;通过 `Arc<Mutex<T>>`、通道和 async/await 实现的安全并发;以及按领域组织的最小化 `pub` 接口。 ## 核心原则 ### 1. 所有权和借用 Rust 的所有权系统在编译时防止数据竞争和内存错误。 ```rust // 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` 实现灵活的所有权 ```rust use 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` 和 `?` —— 切勿在生产环境中使用 `unwrap()` ```rust // 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}"))...

Details

Author
affaan-m
Repository
affaan-m/everything-claude-code
Created
4 months ago
Last Updated
2 days ago
Language
JavaScript
License
MIT

Integrates with

Related Skills