スキル一覧に戻る
PierreZ

rust-patterns

by PierreZ

Collections of claude skills

0🍴 0📅 2026年1月6日
GitHubで見るManusで実行

SKILL.md


name: rust-patterns description: Rust idioms, patterns, and gotchas to write better Rust code allowed-tools:

  • Read
  • Grep
  • Edit
  • Write

Rust Patterns

Practical patterns and pitfalls for writing idiomatic, testable Rust.

Tooling

ContextDoWhy
Running cargo commandsRead .cargo/config.toml for aliasesProjects often define custom aliases for common workflows
CI pipelinefmt --checkclippy -D warningsnextest rundocStandard pre-commit checks in order
Bypassing clippy lint#[expect(lint, reason = "...")] or comment above #[allow(...)]Documents why the lint doesn't apply; reviewable justification
Running testsCheck for .config/nextest.toml; use cargo nextest run if presentFaster parallel execution than cargo test

Error Handling

Instead ofUseWhy
.unwrap().expect("reason") or ? with contextPanics hide bugs; expect documents assumptions; ? propagates properly
Single error messageMessagePair { external, internal }Prevents leaking sensitive info to clients; keeps detail for logs
Library errors as stringsthiserror enums for domain errorsPattern matching for retry logic, client feedback
Bare ? propagation.context() / `.with_context(
Result<T, Error> everywhereType aliases like CreateResult<T>, DeleteResultSelf-documenting API signatures
Retrying all errors uniformlyClassify: BackoffError::Transient(e) vs Permanent(e)Transient = backoff retry, permanent = fail fast
Monolithic error enumNested Result<Result<T, LocalErr>, FatalErr>Separates recoverable failures from system-halting errors

Async & Tokio

PatternExampleGotcha
Explicit runtime ownershipPass Handle explicitly; #[tokio::main] only at entry pointDon't assume runtime exists; don't spawn from arbitrary code
Select-based event loopselect! returns typed Action enum; loop { apply(select().await) }Keep select branches thin; complex logic inside can be cancelled
Prevent futurelockUse channels or tokio::spawn for lock-holding futures in select!select! stops polling losers; stopped future holding lock = deadlock
Channel selectionmpsc bounded (backpressure), oneshot (request-reply), watch (broadcast latest)Avoid unbounded mpsc except sync-to-async bridge

Type Safety

PatternInstead ofUseWhy
Newtype wrappersfn process(job_id: u64, session_id: Uuid)struct JobId(pub u64); + fn process(job: JobId, session: SessionId)Compiler prevents mixing up IDs of same underlying type
Validated newtypespub fields with invariantsPrivate fields + new() -> Result + custom DeserializeInvariants enforced at construction; can't bypass via deserialization
Enum state machinesFlat struct with Option fieldsEnum variants with embedded state-specific dataInvalid states unrepresentable; each state knows its data
Validated transitionsset_state(new) with no checksassert!(valid_transition(old, new))Fail fast on invalid transitions; bugs don't propagate
Cow for flexibilityString or &'static str separatelyCow<'static, str>Accepts both static and owned; avoids allocation for constants
Arc for sharingRc or cloning dataArc<T>Clone+Send shared ownership across threads
Box for dynStack allocation of trait objectsBox<dyn Trait>Single-owner dynamic dispatch; heap when size unknown
Arc::clonearc.clone()Arc::clone(&arc)Makes intent explicit: cheap ref count bump, not deep clone

Trait Design

GuidelineExampleWhy
Dependency abstractiontrait Clock, trait Network with real + sim implsSwap behavior for deterministic tests; enables simulation without mocks
Type witness traitstrait SagaType { type Ctx; type Params; } instead of <Ctx, Params, Output, Error>Bundle related types via associated types; avoids parameter explosion
Consistent API derives#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]Predictable capabilities for API types
Adjacent enum tagging#[serde(tag = "type", content = "value")] or #[serde(tag = "type")]Clear JSON: {"type": "V4", "value": {...}} vs flat {"type": "Create", "name": "foo"}

Testing & Structure

PatternDescriptionBenefit
Short functions (10-30 lines)Decompose into well-named helpers when logic growsReadable, testable, easier to reason about
Semantic suffixes_impl (trait delegation), _inner (non-generic core), for_ (factory), from_/to_ (conversion)Clear intent; _inner enables manual outlining for faster compiles
Closures vs functionsClosures for one-off logic; named functions for reuse or testing.map_err(ActionError::action_failed) over long inline closures
OpContext/RequestContextBundle log, authn, authz into single context with authorize(), child()Consistent logging, auth, tracing; avoids parameter explosion
Simulated implementationsFull alternative impls (e.g., sp-sim/) instead of mock frameworksExercises real code paths; catches integration bugs mocks miss
#[instrument] macroAdd #[tracing::instrument] to functions when using tracingAutomatic span creation with function args; simplifies observability
Sans-IOLogic accepts/returns bytes; caller handles I/OTestable, framework-agnostic; see sans-io.readthedocs.io

Database Patterns

PatternDescriptionWhy
Soft deletestime_deleted TIMESTAMPTZ column (NULL = live)Audit trails + name reuse after deletion
Keyset paginationResultsPage { next_page: Option<String>, items } + WHERE name > last_seenScales with data size; OFFSET scans skipped rows

Project Organization

PatternDescriptionBenefit
Workspace by change frequencySeparate crates for stable (types, utils) vs volatile (app logic) codeIncremental builds; stable crates rarely recompile
Re-export from crate rootpub use error::HttpError; in lib.rsUsers write use crate::HttpError not use crate::error::HttpError

Unsafe Code

RuleExampleWhy
SAFETY comments// SAFETY: pointer is valid because... before every unsafe blockDocuments invariants; required by clippy undocumented_unsafe_blocks

スコア

総合スコア

55/100

リポジトリの品質指標に基づく評価

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

+10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

0/5
タグ

1つ以上のタグが設定されている

0/5

レビュー

💬

レビュー機能は近日公開予定です