/rust:codingfrom rust
Use when writing or reviewing Rust, covering functional design with algebraic types, results, traits, and async effects
Ships in 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.
Read when SKILL.md points to them.
Code treats each crate as part of the language:
thiserror, sysexitsvalidated, nutype, derive_more, strumnonempty-collections, enum-map, itertoolstokio, tokio-util, futuresserde, jiff, rust_decimaltracing[REFERENCES]:
Parameter types state every value a function accepts, and its return type every outcome a caller handles:
.into() in place of an impl Into<T> parameterimpl AsyncFn(A) -> B, filled by an async closure or an async fn passed by name (fetch)macro_rules! differing only in a number, type, flag, or applied function are one function taking it as a parameterbool holds a computed factfield: T = value under default_field_values), and Option holds absence a later owner fillscfg_select! around the differing part, and an item one platform alone holds takes #[cfg]plan >= Plan::Team), and a table holds values no rule derivesenv!("CARGO_PKG_NAME"))fn that is generic, const, recursive, or returns a borrow of a parameter#[expect(<lint>, reason = "<fact>")], and a lint wrong for a whole crate leaves its manifest with that reasonTotal functions produce a declared output for each declared input, a partial one narrowing its input to a constructed type or widening its output:
Tier from a u32 is partial when some counts are invalid, impl From<Quantity> for Tier holds for every constructible QuantityOption<Vec<T>> exists only where a consumer treats no collection and an empty one apartconst { assert!(<test>, "<invariant>") }, failing at monomorphizationPure functions take no async, &mut, or capability trait, and the composition root passes clock readings and host state in:
#[must_use]
pub fn expired(token: &Token, now: Timestamp, leeway: SignedDuration) -> bool { now.duration_since(token.expires) > leeway }
Returned values are one struct literal setting each field, and a step a later step reads is a named let, never a chain a reader must unpick:
impl From<&[Reading]> for Profile {
fn from(readings: &[Reading]) -> Self {
let span = readings.iter().map(|reading| reading.at).minmax().into_option();
let peak = readings.iter().max_by_key(|reading| reading.celsius).map(|reading| reading.sensor);
Self { count: readings.len(), span, peak }
}
}
minmax, counts_by, dedup) in place of a fold or a buffer passfold holds a reduction no member names, never a side collection a second pass zips back by index&held & &stated, |, -, ^) in place of intersection(..).copied().collect()match over their tuple, and an input one arm alone reads goes in its guardlet chain ahead of the matchmap_or, unwrap_or_else) nest no decisionPattern matching keeps recognition, extraction, guards, and results together:
impl Notice {
#[must_use]
pub fn of(delivery: &Delivery, now: Timestamp, recent: SignedDuration) -> Self {
match delivery {
Delivery::Shipped { tracking, .. } => Self::Track(tracking.clone()),
Delivery::Delivered { at } if now.duration_since(*at) < recent => Self::Arrived,
Delivery::Returned { reason, .. } => Self::Refund(*reason),
Delivery::Pending | Delivery::Delivered { .. } => Self::Quiet,
}
}
}
#[non_exhaustive] list every variant in place of a catch-all, a new variant failing each match handling it.., and code tracking each field of a crate's own struct (a renderer) destructures it wholeif let guard bind, never a nested match re-reading a value the arm narrowedunreachable! armas_str or as_slice[] => .., [first, ..] => ..) in place of first, split_last, or a length testOption once near their source, and code matches that typed valueDepth bound and the shape of the work select the form, as Rust guarantees no tail-call elimination:
| [INDEX] | [APPROACH] | [USE_WHEN] | [COST] |
|---|---|---|---|
| [01] | Direct recursion | Small proven depth | Each level holds a stack frame |
| [02] | iter::successors | Unbounded depth, each state read | Holds one state per step |
| [03] | try_fold over a state range | Unbounded depth, final state read | Intermediate states are lost |
| [04] | Arena with typed keys | Shared or cyclic successors | Graph built before the walk |
Stack depth includes native callees and implicit Drop, Clone, and equality traversal.
Types make every constructible value valid, and counting their values (struct counts multiply, enum counts add) exposes states no domain holds.
Each state a consumer inspects is one variant holding exactly the data valid in that state:
#[derive(Debug, Clone, PartialEq, Eq, strum::EnumDiscriminants)]
#[strum_discriminants(name(Stage), derive(PartialOrd, Ord, Hash, enum_map::Enum))]
pub enum Delivery {
Pending,
Shipped { carrier: Carrier, tracking: Tracking },
Delivered { at: Timestamp },
Returned { at: Timestamp, reason: ReturnReason },
}
IntoDiscriminant::discriminant returns a fieldless Stage ranked in declaration order, and EnumMap<Stage, V> holds one value per stageearly_start, late_start) one EnumMapOption fields one state reads become one variant per valid state, and fields read only together one Option of a recordVec of their enum, never a record holding a list per kindResult holds failure alone, and a refused input is a failure, never a warning, a filter_map skip, or a lookup's None read as no constraintClosed, Unset) are an Option around the enum, and foreign sentinels (id 0) become None where they enterRules the domain owns become types whose constructor enforces them, and the inner value is reachable only through that constructor:
nutype declares a validated newtype with its <Name>Error enum, or returns the crate error through validate(with = <fn>, error = <Error>)typed_floats type (tf64::StrictlyPositiveFinite), and nutype holds a rule beyond itderive_more #[as_ref], and public fields hold values no rule across fields constrainsNonZero constant is NonZero::new(<value>).unwrap()Decimal, and time is jiff's Timestamp, Zoned, Span, or SignedDuration, never a float or an integer count of unitsOwnership states who decides a value's lifetime:
IntoIterator<Item: Borrow<T>>, serving a borrowed Vec, an owned one, and iter::once(value) alikeArc<str>, Arc<[T]>, or the handle a dependency states for themCow<'_, T>, the untouched path borrowing its inputFallible transitions borrow the old state and return the next, and infallible ones consume the state and return it (fn held(mut self) -> Self):
impl Account {
pub fn post(&self, amount: Decimal) -> Result<Self, LedgerError> {
let refused = LedgerError::Refused { account: self.id, reason: Refusal::Overflow };
let balance = self.balance.checked_add(amount).ok_or(refused)?;
Ok(Self { balance, ..*self })
}
}
..*self), a foreign default, or a foreign value (..event)Job<R = Option<Retry>>), Job { retry, ..stated } copying the rest&mut self methods stay on a type whose purpose is an owned buffer or an index updated in place (a builder, a parser cursor)Collections follow their most frequent operation:
| [INDEX] | [OPERATION] | [COLLECTION] |
|---|---|---|
| [01] | Ordered reads | Vec<T>, Box<[T]> once frozen |
| [02] | Snapshots shared or versioned | imbl::Vector, imbl::OrdMap |
| [03] | Keyed, insertion order read | IndexMap, IndexSet |
| [04] | Keyed, key order read | BTreeMap, BTreeSet |
| [05] | Keyed, no order read | HashMap, HashSet, Vec over a dense index |
| [06] | One value per enum variant | EnumMap |
| [07] | At least one element | NEVec, NESet |
| [08] | Nodes referring to each other | SlotMap with typed keys |
Every fallible function returns its outcome as a value, and one type serves one concern:
| [INDEX] | [TYPE] | [CONCERN] |
|---|---|---|
| [01] | Option<T> | Absence that holds no reason |
| [02] | Result<T, E> | Expected failure, ? stops at the first |
| [03] | Result<T, NEVec<E>> | Every refusal of one pass |
| [04] | Validated<T, E> | Value built from independent fallible parts |
| [05] | ControlFlow<B, C> | Early exit from a fold with a value |
| [06] | impl Stream<Item = Result<T, E>> | Values over time, each failure one item |
Input boundaries select the result type, functions keep it, and one point converts it by the target's method (ok_or, ok, transpose).
Each step is a function, and its operator follows its signature and whether steps depend on each other:
| [INDEX] | [SIGNATURE] | [OPERATOR] | [BEHAVIOR] |
|---|---|---|---|
| [01] | T -> Result<U, E> | ? in sequence, and_then in a chain | Continues with a dependent step |
| [02] | Option<T> or bool to Result | ok_or, bool::ok_or | Names the error absence means |
| [03] | Independent Results | Validated::from, map2 to map4 | Joins every failure |
| [04] | Items with T -> Result<U, E> | collect::<Result<Vec<U>, E>>() | Stops at the first failure |
| [05] | Items with T -> Result<U, E> | collect::<Validated<Vec<U>, E>>() | Joins every failure |
| [06] | Refusals of checks over one value | NEVec::try_from_vec(all).map_or(Ok(value), Err) | Value, or every refusal |
| [07] | Items, both sides read | partition_result | Splits successes from failures |
impl Iterator<Item = E>, chained and collected onceValidated joins fallible constructions, never a pass rechecking a value its type guaranteesNEVec implements no FromIterator, and a NonEmptyIterator collects into it through FromNonEmptyIteratorResult<(), E> bind as <step>?; in a function or try block, never .and_then(|()| ..)NEVec of element and typed source pairs, never NEVec<Self>Ok::<_, !>(..), and the chain reads its value through into_ok()Panics mark a broken invariant. Refusals are one crate error enum, a variant per relation a caller branches on, and its derived Display is the one place their text is written:
#[derive(Debug, thiserror::Error)]
pub enum LedgerError {
#[error("{account} is {reason}")]
Refused { account: AccountId, reason: Refusal },
#[error("{account} is unreadable")]
Store { account: AccountId, source: io::Error },
}
Refusal is a fieldless enum deriving derive_more::Display under #[display(rename_all = "kebab-case")], its variant names as its text:
Display writes, and branch through fmt::from_fnsource hold the typed foreign error, and text it adds beyond that (a position) is a field the message printsOther(format!(..)) or a FromStr with Err = Stringrename_all printsrename_all = "lowercase" joins a name's words (NonFinite as nonfinite), and a reason of more than one word takes kebab or snake caserename_all = "snake_case" (Input::InitialStep as initial_step)#[source] fault, never a prefix each variant restatesuom into_format_args(<unit>, Abbreviation), bytesize::ByteSize, jiff SignedDuration under {:#}#[error(transparent)] and #[from]map_err a foreign error into its variant beside an operation field and the path or key it omits, alike at every callResult<_, NEVec<E>> take one impl From<E> for NEVec<E>, a single-error step converting through ?io::ErrorKind::NotFound) becomes Ok(None) through one arm matching it aloneErr(_), is_err, and if let Ok drop it unnamedEntry points report each failure as Report::new(&error) (error_reporter), then convert it by value into sysexits::ExitCode:
impl From<LedgerError> for ExitCode {
fn from(value: LedgerError) -> Self {
match value {
LedgerError::Refused { reason: Refusal::Missing, .. } => Self::NoInput,
LedgerError::Refused { reason: Refusal::Overflow | Refusal::Frozen, .. } => Self::DataErr,
LedgerError::Store { source, .. } => source.into(),
}
}
}
Inner layers return failures unreported, and accumulated failures exit with their first item's status.
Traits state a capability a consumer needs, and dispatch follows what varies and who knows the cases:
| [INDEX] | [SITUATION] | [FORM] |
|---|---|---|
| [01] | Closed set of cases the crate knows | enum with a match |
| [02] | Implementation chosen at compile time | Generic parameter with a where bound |
| [03] | One unnamed return type | impl Trait return |
| [04] | Implementation chosen at run time | Box<dyn Trait>, Arc<dyn Trait> |
| [05] | Async capability chosen at run time | dynosaur dynamic type over the trait |
-> impl Future<Output = T> + Send, and implementors write async fntrait_alias)impl on a crate type<Trait>Ext: <Trait> with one blanket impl over T: <Trait> + ?Sized and provided methods continuing a caller's chainfmt::from_fn closure, never a struct holding only a Display implImplementations a derive generates are derived, and a hand-written impl states only behavior no derive covers:
| [INDEX] | [CAPABILITY] | [DERIVE] |
|---|---|---|
| [01] | Error message and source chain | thiserror::Error |
| [02] | Text name and parse of an enum | derive_more Display, FromStr |
| [03] | Variant list, count, discriminants | strum VariantArray, EnumCount, EnumDiscriminants |
| [04] | Checked newtype and its error | nutype |
| [05] | Conversions of an unchecked newtype | derive_more From, Into, AsRef, Display |
| [06] | Traits adding no bound on a generic | derive_where |
| [07] | Wire encode and decode | serde, field conversions through serde_with |
Async functions hold I/O:
JoinQueue, JoinSet, TaskTracker)spawn_blocking or the rayon pool, and a runtime worker runs futures aloneDrop or mem::DropGuard, and DropGuard::dismiss(guard) keeps the value once work commitsValidated, where a ? between them skips every later releaseEffects are independent when the domain says so, and a bound the caller passes sizes each fan-out:
| [INDEX] | [SCENARIO] | [FORM] | [BEHAVIOR] |
|---|---|---|---|
| [01] | Fixed set of independent effects | tokio::join!, then Validated map2 to map4 | Concurrent, joins every failure |
| [02] | Collection of independent effects | buffer_unordered(bound.get()) | At most bound, every failure |
| [03] | Ordered results | buffered(bound.get()) | At most bound, input order |
| [04] | Dependent effects | .await? in sequence | Serial, stops at the first failure |
Tests bind through ? in place of unwrap, assert variants through assert_matches!, name each rstest case, and keep golden output in insta:
#[rstest]
#[case::lowest(1)]
#[case::highest(100)]
fn quantity_within_its_range_is_kept(#[case] count: u32) -> Result<(), QuantityError> {
assert_eq!(Quantity::try_new(count)?.into_inner(), count, "1 to 100 inclusive");
Ok(())
}
Use code:test for test design.
references/async.md (opens in a new tab)references/boundaries.md (opens in a new tab)references/functions.md (opens in a new tab)references/iterators.md (opens in a new tab)references/language-features.md (opens in a new tab)references/numerics.md (opens in a new tab)references/results.md (opens in a new tab)references/traits.md (opens in a new tab)references/types.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub bsamiee/rasm --plugin rust3 skills in this plugin
/debuggingUse when debugging a Rust program, test, or proc macro at runtime, covering debug info profiles, CodeLLDB sessions, panic and abort stops, values and expressions, breakpoints on Rust names, async tasks, undefined behavior checks, and optimized builds/testingUse when writing, editing, fixing, strengthening, pruning, or grading Rust tests, covering flaky tests, fixtures, rstest, proptest, insta, nextest, doubles, real services, and cargo-mutants