Rust
Mandatory guardrails for writing idiomatic, production-quality Rust code. This skill enforces zero-tolerance rules for unwrap()/expect(), correct thiserror vs anyhow usage, ownership and borrowing best practices, visibility minimalism (pub(crate) by default), and idiomatic patterns like the Entry API. Consult this skill for ANY task that writes, modifies, reviews, or refactors Rust code — including .rs files, Cargo.toml edits, CLI tools, libraries, error handling rewrites, and porting code to Rust. It catches the recurring mistakes that LLM-generated Rust makes and produces code that passes clippy and looks like it was written by someone who ships Rust in production.From its SKILL.md
npx -y skills add crustacean-dev/stack-guardrails --skill rustAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
8.1 KB, ~1.8k tokens by cl100k_base, as published. Nobody here has run it
Rust Guardrails
These guardrails apply to all Rust code you write, review, or modify. They exist because LLM-generated Rust tends to repeat the same classes of mistakes: lazy unwrap() calls, unnecessary cloning, overly broad visibility, and sloppy dependency management. Following these rules produces code that compiles cleanly, passes clippy, and looks like it was written by someone who actually ships Rust in production.
Error Handling
Rust's error handling is one of its greatest strengths — but only when used properly. The ? operator exists so you don't have to write boilerplate match arms, and crates like thiserror and anyhow exist so you don't have to hand-roll Display and Error impls.
- Never use
unwrap()orexpect()in production code. These are fine in tests and examples where a panic is acceptable, but in library or application code they're a ticking time bomb. Use?to propagate, or handle the error explicitly. - Always define structured error types with
thiserrorfirst. Every module that can fail should have its own error enum with#[derive(Debug, Error)]and#[error(...)]variants. This gives callers something to pattern-match on and produces clear error messages.thiserroris the right choice for both libraries and applications — the distinction is about whereanyhowfits in, not whether to define error types. - Use
anyhowonly at the application boundary — inmain(), CLI entry points, or top-level orchestration where you're collecting errors from multiple subsystems and just need to report them.anyhow::Resultwraps yourthiserrortypes; it never replaces them. If you find yourself writinganyhow::Resulton an internal function, stop and define a proper error type instead. - Propagate errors with
?— don't writematch result { Ok(v) => v, Err(e) => return Err(e) }whenresult?does the same thing. - Add context with
.context()/.with_context()fromanyhowat the boundary, or usemap_errto convert between yourthiserrortypes deeper in the stack.
Ownership & Borrowing
Unnecessary cloning is the most common sign of "fighting the borrow checker" — it compiles, but it's wasteful and hides design problems. Think about whether a function actually needs to own data before taking it by value.
- No unnecessary
clone()— if you clone, add a comment explaining why (e.g.,// clone needed: value used after move into spawned task). - Prefer
&Tover ownedTin function parameters unless the function genuinely needs ownership (e.g., storing the value in a struct, moving it into a thread). - Use
Cow<'_, str>when a function might or might not need to allocate — this avoids forcing the caller to allocate when they already have a&str. - Prefer
&stroverStringin function parameters. If the caller has aString, they can pass&s; the reverse isn't free. - Prefer
impl Iteratororimpl IntoIteratoroverVecin function parameters — this lets callers pass any iterator without collecting first.
Visibility
Rust defaults to private for good reason. Every pub item is a commitment — it's part of your API surface and can't be removed without a breaking change.
- Minimum visibility by default — use
pub(crate)instead ofpubunless the item is genuinely part of the public API. Leave items private when they don't need to be accessed outside their module. #[must_use]on all functions returningResultorOption— a silently ignored error is a bug waiting to happen.#[non_exhaustive]on public enums and structs that might grow — this lets you add variants or fields without breaking downstream code.
Patterns
- Edition 2021 minimum — there's no reason to target older editions in new code.
#[derive(Debug)]on all types — everything should be debuggable. AddClone,PartialEq,Eq,Hashetc. when semantically appropriate.- Prefer exhaustive
matchover wildcard_— when you enumerate all variants explicitly, the compiler tells you when a new variant is added. Use_only when the set is truly open-ended or when matching on values like integers/strings. - Use
if let/let elseovermatchfor single-variant checks —if let Some(x) = val { ... }is cleaner than a fullmatchwith a_ => {}arm. - Use
HashMap::entry()for insert-or-get patterns — never writeif !map.contains_key(&k) { map.insert(k, v); }whenmap.entry(k).or_insert_with(|| v)does the same thing in one lookup instead of two. The Entry API is also the right tool for counters (*entry.or_insert(0) += 1), default values, and conditional insertion. It's more efficient and signals intent clearly. - Builder pattern for structs with more than 3 fields — constructors with many positional arguments are error-prone and hard to read.
- Prefer
impl Traitoverdyn Traitwhen the concrete type is known at compile time — monomorphization gives better performance and the code is often simpler.
Dependencies
Bad dependency choices haunt a project for years. A few minutes of due diligence saves a lot of pain.
- Prefer well-maintained, widely-used crates:
serde,tokio,tracing,clap,thiserror,anyhow. These have large userbases, good docs, and responsive maintainers. - No yanked or deprecated crates — check before adding a dependency.
- Pin major versions in Cargo.toml — write
tokio = "1"nottokio = "*". Wildcard versions invite breakage. - Use
smol-tomlfor TOML parsing unless you need to preserve formatting/comments during editing (in which casetoml_editis appropriate). Avoid thetomlcrate —smol-tomlis lighter and faster. - Disable default features and enable only what's needed — e.g.,
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros"] }. This keeps compile times and binary size down.
Formatting & Style
cargo fmtcompliant — never fight rustfmt. If a formatting choice feels wrong, it's still better than inconsistency across the codebase.cargo clippyclean — no#[allow(clippy::...)]unless you have a genuine reason, documented with a comment explaining why the lint doesn't apply.- Doc comments (
///) on all public items — types, functions, methods, constants. Explain what it does and when to use it, not how it works internally. - Module-level doc comment (
//!) inlib.rs— this becomes the crate-level documentation.
Unsafe
Rust's safety guarantees are its core value proposition. unsafe should be a last resort, not a convenience.
- No
unsafeunless absolutely necessary — and "the safe version is slightly slower" is almost never a valid reason. - Every
unsafeblock must have a// SAFETY:comment explaining the invariant that makes this safe. This isn't optional — it's how you prove to reviewers (and your future self) that the code is sound.
Testing
#[cfg(test)]module in the same file for unit tests — keep tests close to the code they test.- Integration tests in
tests/directory — these test public API behavior from the outside. - Use
assert_eq!/assert_ne!overassert!(x == y)— the former gives you the actual vs. expected values on failure, which makes debugging far easier. - Test error cases, not just the happy path — if a function returns
Result, write tests that verify the error variants too.
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.