帮助用户掌握 Rust 惯用模式、所有权与并发实践,构建安全高性能应用。
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "rust-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/affaan-m/ECC/main/docs/ja-JP/skills/rust-patterns/SKILL.md 2. 保存为 ~/.claude/skills/rust-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请检查这段 Rust 代码中的错误处理方式,说明 unwrap 和 expect 的风险,并将其重构为使用 Result、? 运算符和自定义错误类型的惯用写法,同时解释这样修改的原因。
一份包含风险说明、重构后代码和最佳实践解释的 Rust 错误处理优化建议。
请用通俗示例解释 Rust 的所有权、借用和生命周期概念,并结合一段小代码说明为什么会出现借用检查错误,以及如何修复。
一份面向学习者的概念讲解,附带示例代码、报错原因和修复方案。
请分析这段 Rust 并发代码在线程安全、性能和可读性方面的问题,比较 Arc、Mutex、RwLock 和 channel 的适用场景,并给出更安全高效的改写建议。
一份并发代码审查结果,包含问题分析、工具选型建议和改进后的实现思路。
安全で高性能かつ保守性の高いアプリケーションを構築するための慣用的なRustパターンとベストプラクティス。
このスキルは6つの重要な領域で慣用的なRustの規約を強制する:コンパイル時のデータ競合防止のための所有権と借用、ライブラリではthiserror、アプリケーションではanyhowを使用したResult/?エラー伝播、不正な状態を表現不可能にする列挙型と完全パターンマッチング、ゼロコスト抽象化のためのトレイトとジェネリクス、Arc<Mutex<T>>、チャンネル、async/awaitによる安全な並行処理、ドメインで整理された最小化されたpubインターフェース。
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 の使用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() を絶対に使わない// 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、アプリケーションエラーには 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 コンビネーターを優先する// 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 {
…
帮助开发者为代码代理配置性能优化、安全防护与研究优先工作流。
提供数据库迁移、回滚与零停机发布的最佳实践指导,适用于多种 ORM 与 SQL 数据库。
通过双评审智能体对结果进行对抗式校验,提升输出发布前的可靠性
帮助你掌握地道 Rust 模式、所有权与并发实践,编写安全高性能应用。
基于 C++ Core Guidelines 编写、审查并重构更安全现代的 C++ 代码。
为 Claude Code 会话提供系统化校验流程,帮助检查结果正确性与质量。
讲解 Rust 惯用模式、所有权与并发实践,帮助构建安全高性能应用
帮助开发者掌握地道 Rust 模式、所有权、并发与错误处理实践
提供惯用Go设计模式与最佳实践,帮助构建稳健高效且易维护的应用
提供惯用 Kotlin 模式与最佳实践,帮助构建稳健高效且易维护的应用
帮助你系统掌握 Rust 测试模式与 TDD 实践,提升代码质量与可维护性。
提供地道 Go 语言模式与最佳实践,帮助构建健壮高效且易维护的应用