hexjasur/AGENTS.md / skills/rust-best-practices
rust-best-practices
VerifiedRust Best Practices
Let the compiler carry the design: encode invariants in types, return errors instead of panicking, and keep unsafe out unless it is isolated and justified. Prefer the simplest ownership model that works before reaching for Arc<Mutex<_>> or lifetimes.
Procedure
- [ ] 1. Read Cargo.toml, edition, MSRV, features, and the existing error and async style
- [ ] 2. Model data with types and make invalid states unrepresentable
- [ ] 3. Return Result with a typed error; no unwrap in non-test code
- [ ] 4. Choose ownership: borrow first, clone deliberately, share only when needed
- [ ] 5. Keep async code non-blocking and cancellation-safe
- [ ] 6. Run fmt, clippy, tests, and dependency audits
- [ ] 7. Check the release profile and binary size when it matters
- Follow the project's edition,
rust-version, workspace layout, and error crate. Checkcargo tree -dfor duplicate versions before adding a dependency. - Use enums for states, newtypes for validated values (
struct UserId(u64)), andOptionfor absence. Parse input into a typed value once at the boundary instead of passing raw strings around. - Libraries define an error enum with
thiserror; applications and command handlers may useanyhowwith.context(...). Use?for propagation. In Tauri commands, map errors to a serializable type; never return internal paths or secrets to the frontend. - Accept
&str,&[T], and&Pathin parameters, return owned values. Clone only when ownership is truly needed and say why in review. UseCowwhen a function sometimes allocates. Reach forArconly for data shared across threads or tasks, and prefer message passing over shared mutable state. - Never call blocking code (file reads, heavy compute,
std::thread::sleep) on an async executor thread; usespawn_blockingor an async API. Do not hold astd::sync::Mutexguard across.await. Make futures safe to drop, and bound channels and concurrency. - Run
cargo fmt --check,cargo clippy --all-targets --all-features -- -D warnings,cargo test, andcargo doc --no-depsfor library crates. Addcargo auditandcargo deny checkin CI. - For shipped binaries, set a release profile (
lto,codegen-units = 1,strip,opt-level,panic = "abort"only if acceptable) and measure the size before and after.
Guardrails
- Never use
unwrap()orexpect()on input, I/O, or parsing outside tests, examples, and proven invariants (document the invariant in theexpectmessage). - Never write
unsafewithout a// SAFETY:comment stating the invariant, and keep it in the smallest function that can uphold it. - Never silence clippy with a blanket
#![allow(...)]; allow a single lint on a single item with a reason. - Never hold a lock across an
.await, and never block the async runtime. - Never build shell commands or file paths by string concatenation with untrusted data; use
Command::argandPath::joinwith validation. - Never log secrets or tokens, and never
derive(Debug)on a type that holds them without redaction. - Do not use
panic!for recoverable errors, and do not ignore aResultwithlet _ =without a comment. - Do not add a dependency for a few lines of code, and do not publish crates or cut releases without explicit instruction.
Gotchas
- A borrow checker fight often means the data layout is wrong. Split the struct, pass fields separately, restructure ownership, or use indices instead of references; do not add
clone()to silence it blindly. Stringslicing by byte index panics on non-ASCII text. Usechars(),char_indices(), orstr::get.- Integer overflow wraps in release builds. Use
checked_*,saturating_*, orwrapping_*explicitly where input is untrusted. tokio::spawnneeds'static + Sendfutures; borrowed data andRcorstd::sync::MutexGuardacross.awaitfail here.select!can drop a branch's future mid-work. Make that work cancellation-safe or move it to a task.- Feature unification means one crate enabling a feature enables it for everyone. Test with
--no-default-featuresand--all-features. cargo updatecan break the build; commitCargo.lockfor applications and review the diff.- Clippy suggestions can change behavior (for example removing a clone that preserved a snapshot). Run tests after applying them.
Report format
State what changed, the error and ownership design chosen, which commands ran (fmt, clippy, test, audit), and what was not run. List findings by severity (unsound or panic path, blocking in async, leaked secret, missing context, style), each with location and fix.
Read references/rust-reference.md for error type, async, Tauri command, CI, and release profile snippets and sources.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |