ワンクリックで
rust-idioms
Rust ownership, tokio, thiserror/anyhow, Clippy pedantic, unsafe, lifetimes.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Rust ownership, tokio, thiserror/anyhow, Clippy pedantic, unsafe, lifetimes.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
Structured fault tolerance for coordinator agents. 5-level escalation ladder (Retry → Replace → Skip → Redistribute → Degrade), dead-man timers, degraded completion protocol, and cross-level escalation format. Load when orchestrating agents that may fail.
Structured code review protocol for inspecting code quality against the full rule set. Use when auditing code written by yourself or another agent, during the /audit workflow, or when the user asks for a code review.
Reusable convergence protocol for coordinator agents. Defines the BRIEFING → ITERATE → GATE → CONVERGE loop, context hygiene rules, self-succession protocol, turn budget, and handoff compression. Load when orchestrating multi-iteration workflows.
Pre-flight checklist and post-implementation self-review protocol. Use before generating any code (pre-flight) and after writing code but before verification (self-review) to catch issues early.
MECE task decomposition, file ownership enforcement, DAG-based execution, and safe merge protocol for intra-domain parallel dispatch. The safety invariants that prevent merge chaos when multiple agents write in parallel. Applies recursively at every nesting depth.
Shared protocols for all agents in the multi-agent pipeline: recursive nesting, pre-implementation restatement, parallel dispatch format, and agent definition cascade. Load this skill instead of inlining these protocols in every agent file.
| name | rust-idioms |
| description | Rust ownership, tokio, thiserror/anyhow, Clippy pedantic, unsafe, lifetimes. |
| paths | ["**/*.rs","**/Cargo.toml"] |
Rust's type system and ownership model are your primary tools for correctness. Lean into the compiler — it is your strongest ally. Write code that is idiomatic, safe, and expressive.
Scope: This file covers Rust-specific coding idioms. For file layout, see
references/project-structure.md. For test naming conventions, seetesting-strategy.md. For logging library choice, see @.agents/skills/logging-implementation/SKILL.md.
Prefer borrowing (&T, &mut T) over cloning
.clone() to silence the borrow checker without a // CLONE: comment explaining whyCow<'_, T> when a function may or may not need ownership&str over String in function parameters, &[T] over Vec<T>Minimize owned data in structs
String, Vec<T>) when the struct must outlive its inputsAvoid unnecessary Arc<Mutex<T>>
tokio::sync::mpsc)RwLock over MutexArc<T> without a lockUse the ? operator for propagation — never unwrap() in production code
unwrap() and expect() are acceptable only in:
#[test], #[tokio::test])// SAFETY: comment)main() function with clear error messages via expect("reason")Choose error crates by context:
thiserror — define typed error enumsanyhow — ergonomic error chaininganyhowError type design:
// ✅ Good — typed, matchable errors
#[derive(Debug, thiserror::Error)]
pub enum PathfinderError {
#[error("file not found: {path}")]
FileNotFound { path: PathBuf },
#[error("AST parse failed: {0}")]
ParseError(String),
#[error(transparent)]
Io(#[from] std::io::Error),
}
// ❌ Bad — stringly-typed, unmatchable
fn do_thing() -> Result<(), String> { ... }
// ✅ Annotate public Result-producing functions to force callers to handle them
#[must_use]
pub fn create_task(req: CreateTaskRequest) -> Result<Task, TaskError> { ... }
// Triggers a compiler warning when the return value is fully ignored:
// create_task(req); // warning: unused `Result` that must be used
//
// This does NOT trigger the warning (intentional discard — still valid when used deliberately):
// let _ = create_task(req); // explicit discard, silences warning by design
Use tokio as the async runtime
#[tokio::main] or #[tokio::test]tokio::spawn for concurrent tasks, not std::thread::spawntokio::select! for racing futures, not manual pollingCancellation safety:
tokio::sync::mpsc over tokio::sync::broadcast unless fan-out is neededasync fn that holds resources across .awaittokio_util::sync::CancellationToken for graceful shutdownBlocking operations:
tokio::task::spawn_blocking for CPU-heavy or blocking worktokio::fs instead of std::fs inside async functionsZero unsafe blocks unless in FFI boundaries
unsafe block must have a // SAFETY: comment explaining the invariantMinimize unsafe surface area:
unsafe in a safe wrapper functionunsafe wrappersNever use unsafe to bypass the borrow checker — restructure the code instead
Prefer '_ lifetime elision when possible
'a for single lifetime parameters, descriptive names ('input, 'query) for multipleKeep generic bounds simple:
impl Trait in argument position for simple caseswhere clauses for complex bounds — never inline complex bounds in <...>Avoid lifetime gymnastics:
ArcBuilder pattern for types with many optional fields:
Self from builder methods for chainingbuild() returns Result<T, BuildError>, not TNewtype pattern for domain types:
struct UserId(u64), not bare u64Deref only when the newtype truly "is-a" the inner typeTypestate pattern for state machines:
From/Into conversions:
From<A> for B (never Into directly)impl From<X> for Error with thiserror's #[from] attributeTest organization (Rust-specific — differs from Go/TS):
#[cfg(test)] mod tests block at the bottom of each .rs file — this is the idiomatic Rust convention, not a shortcut
use super::*#[cfg(test)] is stripped from production builds*_test.rs files — this breaks private access and is non-idiomatictests/ directory at crate root (each file compiled as a separate crate)
use my_crate::function;#[cfg(test)] annotation neededtests/common/mod.rs (NOT tests/common.rs, which Cargo treats as a test file)#[tokio::test] for async testsTest naming: fn test_<function>_<scenario>_<expected>() (snake_case)
Assertions:
assert_eq! / assert_ne! over assert!(a == b) — better error messagesassert!(matches!(result, Ok(_))) for enum variant checkingProperty testing: Use proptest or quickcheck for functions with wide input spaces
cargo check for fast iteration during development
cargo check: type-checks without producing a binary — fastest feedback loopcargo clippy: includes cargo check plus lint rules — use before committingcargo build: only when you need the actual binary/library artifactcargo build during TDD cycles — it is significantly slower than cargo checkcargo clippy must pass with zero warnings before any commit
#[allow(clippy::...)] only with a // ALLOW: comment explaining whycargo fmt is non-negotiable — all code must be formatted
Recommended project-level Clippy configuration (.clippy.toml or Cargo.toml):
[lints.clippy]
pedantic = "warn"
unwrap_used = "deny"
expect_used = "warn"
Cargo.toml — use dep = "1" not dep = "*"cargo audit to check for known vulnerabilities