/dd:rust:corefrom dd:rust
Core Rust conventions for type design, error handling, ownership, async/tokio, module layout, comments, code style, and naming. Load first when writing, changing, or reviewing Rust code.
Ships in dd:rust. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The conventions that govern essentially every Rust edit. Topic skills stack on top:
dd:rust:serde, dd:rust:testing, dd:rust:linting, dd:rust:performance.
struct UserId(u64)#[repr(transparent)] for FFI-safe newtypesOption<T> for nullable values — compiler forces None handlingimpl blocks, not struct definitionswhere clauses for complex multi-bound signaturesFromStr), work with types internallyFrom/TryFrom for type conversions instead of ad-hoc fn convert_x_to_y() / transformer helpers — you get Into/TryInto for free and standard call sites (.into(), x.try_into()?)From for infallible conversions, TryFrom (with an error type) when conversion can fail — never a bespoke function returning Result for what TryFrom models#[must_use] on builder methods and functions returning values that should not be ignoredprivate modulestruct Locked; struct Unlocked; — encode state transitions in the type systemResult<T, E> for all fallible operations — propagate with ?unwrap(), expect(), or panic!() — enable clippy::unwrap_used and clippy::expect_used#[derive(thiserror::Error)] enums for typed, matchable errorsanyhow::Result with .context() / .with_context() for flexible error chains#[from] for automatic From impl + source chain#[source] when you need extra context fields alongside the cause.context() / .with_context() at call sites for runtime context.map_err(Error::from) or ? (via #[from]), not a match that rewraps each varianttracing::error! where you decide what to do with the error, not where you propagate it with ?.with_context(|| format!("failed to process {id}")) — lazy formatting avoids cost on success path&T over .clone() — clone only when storing data or sending across threads&str not &String, &[T] not &Vec<T>, &Path not &PathBuf'_ for inferredRc in single-thread code, Arc only when crossing thread boundariesCow<'_, T> when mutation is rare — zero-cost when no modification neededRefCell<T> single-thread, Mutex<T> multi-thread. Consider parking_lot::Mutex for no poisoningRwLock for read-heavy workloads; switch to Mutex if writes >20%Copy on small types (≤16 bytes) with no Dropclone_from() to reuse existing allocations.clone() calls explicit and visible — they signal heap allocation costlet x = &temp().field; may not live long enough. Bind the temporary first: let tmp = temp(); let x = &tmp.field;&*ref or &mut *ref reborrows instead of moving — useful for passing &mut to functions without losing ownership of the mutable referencetokio runtime: multi-thread for servers, current_thread for CLIsspawn_blocking() for CPU-heavy or sync I/O operations (>1ms)tokio::fs not std::fs in async codejoin! / try_join! for independent futures — fail-fast on first errorJoinSet for dynamic task collections — auto-aborts remaining on dropselect! for racing futures: timeouts, cancellation, fallbacksCancellationToken from tokio_util for hierarchical graceful shutdownSemaphore or buffer_unordered()mpsc — unbounded grows without limitoneshot::Sender in request structs for reply patternswatch channel for config/status where slow receivers skip to latest.await — clone data out, release lock, then awaittokio::sync::Mutex in async code, not std::sync::MutexJoinHandle errors — spawn returns JoinHandle<T>, .await returns Result<T, JoinError>. Always handle the JoinError (task panicked or was cancelled)tokio_stream::StreamExt for async iteration — .next().await, .map(), .filter(), .take()-> Pin<Box<dyn Future<Output = T> + Send>> — required because async fn in traits is not yet fully stable in all contextscontrollers/, models/ dirs)main.rs is a thin entry point — all logic in lib.rs for testabilityCargo.lock, build cache)[workspace.dependencies], sub-crates use { workspace = true }pub usepub surfacepub(crate) for internal sharing, pub(super) for parent-only accessfoo.rs) over foo/mod.rs — cleaner, less nestingfoo/mod.rs only when the module has submodulessnake_case — match the file name exactlyDefault to less — well-named code beats a comment. But a workspace with missing_docs = "warn" and rustdoc under -D warnings needs a doc on every public item, so shorten them, never delete them.
The failure to avoid is the comment poem: a prose block above a file or function, explaining the design to nobody.
//! module header — 1 line. /// item doc — 1 line. // inline — 1–3 lines./// Returns the config. on fn config() is noise. A public item still needs one line, so make it say what the name doesn't.///, one line by default — say what it does / what it returns, not how it works. The signature already shows the types; don't restate them. Struct fields get a short line each, not a paragraph.fn doc starts with a third-person verb — Builds…, Returns…, Resolves… — never a noun phrase ("The live agent this request addresses…") and never the imperative ("Build the router"). Only types, fields, and consts may stay noun phrases.# Arguments / # Returns sections restating the signature. Keep # Errors / # Panics / # Safety only when the behavior is non-obvious.//! is one line: what the module is. No architecture essays, no cross-module narration. Design rationale lives in a design doc (~/.context/, docs/), not the file head. A thin module the name already explains (a CLI subcommand, a re-exporting mod.rs) can skip it.// that restate the code. // increment the counter above count += 1 is noise. Keep a // only for a non-obvious why: a workaround, a subtle ordering requirement, a spec reference, a deliberate deviation. If it explains what a block does, extract a well-named function instead.//! headers to one line, strip restating //. Never strip a public item's doc to nothing — that breaks the missing_docs gate.// Too much — restates the type, over-explains an internal alias
/// A boxed, thread-safe error cause — what a [`PolicyStoreError`] carries as its
/// source, kept whole so the backend's error chain survives to the log site.
type BoxError = Box<dyn StdError + Send + Sync + 'static>;
// Enough
/// Boxed error cause carried by [`PolicyStoreError`], kept whole for the log site.
type BoxError = Box<dyn StdError + Send + Sync + 'static>;
// Too much — a 4-line doc on a 3-line function
/// The centered, capped column text renders into — CSS `max-width` + `margin: 0 auto`.
///
/// An odd gutter's remainder goes right, so the column doesn't jitter as the pane resizes.
/// Highlights live inside this rect; chrome (border, footer) spans the pane.
pub fn content_column(area: Rect) -> Rect {
// Enough — the jitter rule is the one thing the signature can't show
/// Returns the centered, width-capped column for text. An odd gutter's remainder
/// goes right, so the column doesn't jitter on resize.
pub fn content_column(area: Rect) -> Rect {
// Too much — a 9-line design essay at the top of every file
//! The policy persistence contract.
//!
//! [`PolicyStore`] is the seam between the engine and durable storage: the crate
//! only *defines* it, the binary implements it over the Postgres pool ...
//! (six more lines)
// Enough
//! Policy persistence contract — [`PolicyStore`], implemented over Postgres by the binary.
match when combinators work — prefer .map(), .and_then(), .unwrap_or(), ? over match blocks. A match whose arms only log and return the same value is the most common offender: .inspect_err() logs the error, .ok()? drops it, .or_else() logs the empty case. If the function returns () and ? is unavailable, use let ... else — not a match.// Nested — three arms, two of them just log
match ctx.upstream.pick_snark().await {
Ok(Some(payload)) => Some(payload),
Ok(None) => {
tracing::debug!("no SNARK job upstream");
None
}
Err(err) => {
tracing::warn!(error = %format_args!("{err:#}"), "failed to collect a SNARK job");
None
}
}
// Flat — same three cases, no nesting
ctx.upstream
.pick_snark()
.await
.inspect_err(|err| {
tracing::warn!(error = %format_args!("{err:#}"), "failed to collect a SNARK job");
})
.ok()?
.or_else(|| {
tracing::debug!("no SNARK job upstream");
None
})
Both arms producing a value is not an excuse — that is what map_or_else is for. Binding e in the Err arm only to format or log it is not "real work"; it is the closure argument.
// Still a match — both arms just build a string
self.status = match saved {
Ok(()) => "quote parked. q to close, answer the prompt, then reopen".to_owned(),
Err(e) => format!("the quote could not be parked: {e:#}"),
};
// map_or_else — err closure first, ok closure second
self.status = saved.map_or_else(
|e| format!("the quote could not be parked: {e:#}"),
|()| "quote parked. q to close, answer the prompt, then reopen".to_owned(),
);
Reach for the combinator that matches the shape:
| Shape | Use |
|---|---|
| both arms produce a value | map_or_else |
| one arm is a constant/default | map_or, unwrap_or, unwrap_or_default |
| one arm computes a fallback | unwrap_or_else |
| transform only the success | map, and_then |
| transform only the error | map_err |
| log, then drop | inspect_err(…).ok() |
| propagate | ? |
Option from a fallible call | .ok(), .ok_or_else() |
Keep the match only when arms do genuinely different work (not just building different values of the same type), or the compiler's exhaustiveness check is the point — matching a state enum with three or more variants.
.filter(), .map(), .fold() over for loopsreturn/continue/break (guard clauses). Less nesting = easier to readelse — almost never needed. Invert the condition and return/continue early. else adds nesting and cognitive load. Rare exceptions are fine, but default to no elseThis holds just as hard when the if/else sits in expression position wrapped in a constructor — Ok(if c { a } else { b }), Some(if …), a let x = if …. The wrapper is what makes the else look unavoidable: it isn't. Sink the wrapper into an early return and the common case lands on the last line, unindented.
// The Ok(…) hides a guard clause — both outcomes indented, else in the middle
fn stage_timer() -> CudaResult<StageTimer> {
Ok(if is_dry_run()? {
StageTimer::silent()
} else {
StageTimer::new()
})
}
// Guard clause — the special case exits, the normal path is the last line
fn stage_timer() -> CudaResult<StageTimer> {
if is_dry_run()? {
return Ok(StageTimer::silent());
}
Ok(StageTimer::new())
}
Repeating the Ok( is the price, and it is worth it: the reader sees the exceptional case handled and dismissed, then the answer. Two branches of a ternary read as "pick one"; a guard reads as "unless…, this."
use per crate — merge everything from the same crate into a single braced import, then group std / external / local with a blank line between. Stable rustfmt cannot do this (imports_granularity is nightly-only), so write it merged by hand and keep it that way when adding an import.// Scattered — four lines, two crates
use std::future::Future;
use std::sync::Arc;
use jobs::SnarkRun;
use jobs::dto::SnarkJobPayload;
// Merged — one use per crate, grouped std / external / local
use std::{future::Future, sync::Arc};
use jobs::{SnarkRun, dto::SnarkJobPayload};
use tokio_util::sync::CancellationToken;
use crate::context::Context;
#[allow(clippy::too_many_arguments)]rustfmt never adds a blank line, so this is on you. Lines that do one step stay together; a blank line goes between steps. A block (if, match, for, loop) is its own paragraph — a blank line before and after, except as the first or last statement of a body. Consecutive guard clauses are one paragraph. A body of ~4 simple statements stays tight.fn, a const, or a wrapper. The same cleanup in two branches → one exit path. A second implementation of what a module already does → extend that module.HttpServer, JsonParser — not HTTPServeras_ = free borrow (O(1)), to_ = allocates/computes, into_ = consumes selfget_ prefix for simple field accessors — use fn name(&self) -> &strget_ for lookups, bounds checks, fallible operationsiter() → &T, iter_mut() → &mut T, into_iter() → Titer() → Iter, keys() → KeysCamelCase — describe capability, not implementation-able suffix for capabilities: Readable, Parseable, ConnectableIs-/Has- only for marker traits: IsEmpty, HasIdHandler or Processor — be specific: RequestHandler, EventProcessorSCREAMING_SNAKE_CASE: const MAX_RETRIES: u32 = 3CamelCase: type Result<T> = std::result::Result<T, MyError>kebab-case in Cargo.toml: my-featureserde, tokio-runtimefull = enables everything, default = minimal useful setWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
npx claudepluginhub napalmpapalam/skills --plugin rust6 skills in this plugin
/lintingRust workspace lint configuration, clippy enforcement, and formatting rules. Use whenever setting up or modifying Cargo.toml lint configuration, configuring clippy or rustfmt, adding CI checks for Rust, or when the user asks about lint rules, formatting settings, or workspace-level lint inheritance./performanceRust performance — iterators, release profiles, inlining, cache layout, bounds checks, allocation profiling. Use whenever optimizing Rust code, choosing between iterators and loops, configuring release profiles, adding inline hints, profiling allocations, or when the user asks about performance patterns, benchmarking, or hot-path optimization in Rust./reviewComprehensive Rust code review — runs cargo checks, loads all Rust convention skills, reviews changes, and generates a structured report. Use when reviewing finished Rust changes, closing a slice that touched Rust, preparing a PR for merge, or auditing Rust code quality — not while writing the code./serdeRust serde serialization — derive patterns, snake_case defaults, enum representations, attributes, zero-copy deserialization. Use whenever working with serde in Rust, adding Serialize/Deserialize derives, configuring JSON/YAML/TOML serialization, handling optional fields, choosing enum representations, or when the user asks about serde attributes, custom serializers, or data format conversion in Rust./testingRust testing — unit/integration layout, mocking with mockall, async test patterns, property testing, snapshot testing. Use whenever writing or reviewing Rust tests, setting up test infrastructure, choosing mocking strategies, organizing test modules, debugging test failures, or when the user asks about testing patterns, coverage, or test utilities in Rust projects.