帮助你掌握地道 Rust 模式、所有权与并发实践,编写安全高性能应用。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "rust-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/.kiro/skills/rust-patterns/SKILL.md 2. 保存为 ~/.claude/skills/rust-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请检查这段 Rust 代码中的错误处理方式,将 unwrap 和 panic 重构为更地道的 Result/thiserror/anyhow 模式,并解释这样改的原因。
返回一版更安全的 Rust 实现,并说明错误传播、类型设计和可维护性改进点。
我遇到了 Rust 编译器的借用检查错误。请分析这段代码中所有权、可变借用和生命周期的冲突,并给出两种修复方案。
输出问题根因分析,并给出可运行的修改方案与各自权衡说明。
请为一个高吞吐日志处理服务设计 Rust 并发方案,比较线程、async/await、channel、Arc<Mutex<_>> 等模式,并给出推荐实现骨架。
给出并发架构建议、模式对比、性能与安全考量,以及示例代码骨架。
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),
…
帮助开发者为代码代理配置性能优化、安全防护与研究优先工作流。
为 Claude Code 会话提供系统化校验流程,帮助检查结果正确性与质量。
通过双评审智能体对结果进行对抗式校验,提升输出发布前的可靠性
基于 C++ Core Guidelines 编写、审查并重构更安全现代的 C++ 代码。
提供数据库迁移、回滚与零停机发布的最佳实践指导,适用于多种 ORM 与 SQL 数据库。
帮助开发者掌握后端架构模式、API 设计与数据库性能优化实践
帮助开发者掌握地道 Rust 模式、所有权、并发与错误处理实践
讲解 Rust 惯用模式、所有权与并发实践,帮助构建安全高性能应用
帮助用户掌握 Rust 惯用模式、所有权与并发实践,构建安全高性能应用。
提供地道 Kotlin 模式与最佳实践,帮助构建健壮高效且易维护的应用。
提供地道 Go 语言模式与最佳实践,帮助构建健壮高效且易维护的应用
提供地道 Go 设计模式与最佳实践,帮助编写健壮高效且易维护的应用