rust-best-practices
Skill91 starsChanged 5 days agoApache-2.0View on GitHub
Development guidance for writing idiomatic, performant, and safe Rust. Use when writing new Rust modules, designing library APIs, configuring Cargo workspace lints and features, optimizing monomorphization or cache alignment, or migrating to Rust Edition 2024.
57 other projects use a version of this.
Adopted by
Most recently taken up by
- salasebas/skillstheir own version, first seen Nov 29, 2026
- nooblk-98/burnbartheir own version, first seen Nov 29, 2026
- Furyfree/ai-workflowtheir own version, first seen Nov 29, 2026
- sshine/managed-skillstheir own version, first seen Nov 29, 2026
- TudorAndrei/skillstheir own version, first seen Nov 29, 2026
- sajaddp/sonjoo-seo-audittheir own version, first seen Nov 29, 2026
Used with
Projects with it also use rust-port, rust-async-patterns and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
fedemeloSkillrust-port
Port code from C, C++, Python, Go, JavaScript, or TypeScript into idiomatic Rust that keeps the original behavior: ownership instead of manual memory, Result instead of error codes and exceptions, enums instead of flag ints and magic strings, and tests that prove the port matches. Use this whenever the user asks to port, translate, convert, migrate, or rewrite code in Rust ("rewrite this in Rust", "what would this look like in Rust", "move this module to Rust"), even if they don't say "port". Pairs with the rust-best-practices skill, which covers the target code's style.
Also in 5 projects that use this
klauswgSkillrust-async-patterns
Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.
Also in 11 projects that use this
GitHubSkillrust-mcp-server-generator
Generate a complete Rust Model Context Protocol server project with tools, prompts, resources, and tests using the official rmcp SDK
Also in 3 projects that use this
CloudflareSkillrust-review
Rust code review for workerd. Covers CXX FFI safety, unsafe code patterns, JSG resource conventions, error handling, and a review checklist adapted from the C++ review skills. Load this skill when reviewing Rust code in src/rust/.
Also in 6 projects that use this
huialiSkillrust-testing
Also in 9 projects that use this
gihwan-devSkilltauri-v2
Tauri v2 cross-platform app development with Rust backend. Use when configuring tauri.conf.json, implementing Rust commands (#[tauri::command]), setting up IPC patterns (invoke, emit, channels), configuring permissions/capabilities, troubleshooting build issues, or deploying desktop/mobile apps. Triggers on Tauri, src-tauri, invoke, emit, capabilities.json.
Also in 7 projects that use this
Other versions57 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 57
- farm-fe/farm★ 5.6ksame name
- crbnos/carbon★ 2.9ksame name
- morganlinton/BeautifulRust★ 1.8ksame name
- pedronauck/skills★ 659same name
- Cosmian/kms★ 380same name
- openbezal/rhema★ 354same name
- apollographql/apollo-mcp-server★ 323same name
- apollographql/skills★ 138same name
- microsoft/scope★ 93same name
- Blushyes/reef★ 84same name
47 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository85 other files it gives its agents.
- AGENTS.mdAGENTS.md
- llms.txtllms.txt
- agent-architecture-analysisSkill
- app-intents-code-reviewSkill
- artifact-analysisSkill
- axum-code-reviewSkill
- brainstorm-beagleSkill
- bubbletea-code-reviewSkill
- cloudkit-code-reviewSkill
- elixir-performance-reviewSkill
- elixir-security-reviewSkill
- elixir-writing-docsSkill
- exdoc-configSkill
- exunit-code-reviewSkill
- fastapi-code-reviewSkill
- fetch-pr-feedbackSkill
- ffi-code-reviewSkill
- fix-llm-artifactsSkill
- fowler-refactoringSkill
- gen-test-planSkill
- go-architectSkill
- go-code-reviewSkill
- go-data-persistenceSkill
- go-testing-code-reviewSkill
- healthkit-code-reviewSkill
- humanize-beagleSkill
- improve-docSkill
- ios-animation-code-reviewSkill
- liveview-code-reviewSkill
- llm-artifacts-detectionSkill
- llm-judgeSkill
- macros-code-reviewSkill
- phoenix-code-reviewSkill
- postgres-code-reviewSkill
- prfaq-beagleSkill
- prometheus-go-code-reviewSkill
- pytest-code-reviewSkill
- quick-planSkill
- react-flow-code-reviewSkill
- react-flowSkill
- react-router-code-reviewSkill
- react-router-v7Skill
- receive-feedbackSkill
- refactor-repoSkill
- resolve-beagleSkill
- respond-pr-feedbackSkill
- review-ai-writingSkill
- review-elixirSkill
- review-frontendSkill
- review-goSkill
- review-iosSkill
- review-llm-artifactsSkill
- review-planSkill
- review-pythonSkill
- review-remix-v2Skill
- review-rustSkill
- review-skillSkill
- review-structureSkill
- review-tuiSkill
- review-verification-protocolSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
6 rules. 0 are common, 0 are distinctive, and 6 are very specific to this project.
0
Common
Most of the 56 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 38
Run cargo doc --no-deps for the crate you edited (add -p <crate> in workspaces).
- Very specific: line 47
Error crates: Use thiserror in libraries (structured enums callers can match on), anyhow in binaries/CLIs (ergonomic context chaining), and …
- Very specific: line 48
Auditing: Run cargo-deny in CI for licenses, advisories, and duplicate bans.
- Very specific: line 60
Run cargo clippy --all-targets --all-features -- -D warnings on every commit.
- Very specific: line 68
Use static dispatch (impl Trait / <T: Trait>) by default.
- Very specific: line 72
Document public items with # Examples, # Errors, # Panics, and # Safety, remember cargo nextest skips doctests (cargo test --doc), and use …
“Common” is measured: kept by at least 6 in 10 of the 56 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rust Best Practices
Guidance for writing idiomatic, performant, and safe Rust code. This is a development skill, not a review skill -- use it when building, not reviewing.
Quick Reference
| Topic | Key Rule | Reference |
| Idioms & Edition 2024 | LazyLock/OnceLock, Edition 2024 rules, drop guards, extension traits, index pointers, preludes | references/coding-idioms.md |
| Clippy | Run cargo clippy -- -D warnings; set priority = -1 on lint groups in [workspace.lints.clippy] | references/clippy-config.md |
| Performance | Profile --release; watch monomorphization budgets, cache-line alignment, std::hint::black_box | references/performance.md |
| Generics & Dispatch | Edition 2024 RPIT + use<>, AFIT vs async-trait, variance, dyn compatibility, blanket impls | references/generics-dispatch.md |
| Documentation | /// sections, nextest --doc caveat, #[diagnostic::on_unimplemented], doc lints | references/documentation.md |
| API Design | Unsurprising, flexible, obvious, constrained — hidden contracts, sealed traits, fallible close() | references/api-design.md |
Gates
Short sequences with pass conditions before claiming outcomes that need evidence (not an internal “I checked”).
Clippy clean
- From the workspace root (or with
-p <crate>), run:cargo clippy --all-targets --all-features -- -D warnings. - Pass: exit status is
0and the invocation finishes without Clippy-deny failures.
Performance claim
- Build with
cargo build --release(or your benchmark harness) under the same profile you ship or measure. - Capture a before and after number from the same tool and metric (name both), e.g. Criterion
ns/iter,heaptrackallocations, or a flamegraph path on disk. - Pass: you can cite both measurements, or you explicitly state that only correctness or readability changed and you are not claiming a performance delta.
Docs for symbols you changed
- Run
cargo doc --no-depsfor the crate you edited (add-p <crate>in workspaces). - Pass: the doc build succeeds; if
# applies, there are no new missing-doc errors for those symbols.
Coding Idioms & Edition 2024
Borrow by default, prefer std::sync::LazyLock / OnceLock (stable since 1.80) over once_cell / lazy_static, and watch Edition 2024 changes (gen reserved keyword, if let / tail temporary drop order, ! fallback). For scoped state changes, use drop guards (let _guard = ..., never let _ = ...) with mem::replace or scopeguard::defer!. Add methods to foreign types via extension traits, prefer index pointers (slotmap::DefaultKey) for cyclic graphs without unsafe, and curate a lean crate prelude (additions are semver-minor per RFC 1105). See references/coding-idioms.md.
Error Handling & Crate Hygiene
- Error crates: Use
thiserrorin libraries (structured enums callers can match on),anyhowin binaries/CLIs (ergonomic context chaining), andeyrewhen custom error reporters are needed. Never exposeanyhow::Errorin a library's public API. - Auditing: Run
cargo-denyin CI for licenses, advisories, and duplicate bans; usecargo-machete(works on stable) orcargo-udeps(nightly) to prune unused dependencies.
Cargo Feature & Workspace Pitfalls
- Use
dep:syntax (Rust 1.60+) for optional dependencies (json = ["dep:serde_json"]) so dependency names do not leak into your public feature namespace. - Keep features additive: Cargo takes the union of all enabled features across the dependency graph; verify combinations compile with
cargo hack check --feature-powerset --no-dev-depsand verify MSRV lower bounds withcargo +nightly update -Z minimal-versions && cargo +nightly check. [target.'cfg(feature = "...")'.dependencies]is silently ignored — dependency resolution runs before features are evaluated; useoptional = true+[features]instead.- Workspace
pathvs crates.ioversionidentity: Depending on a sibling viapath = "../foo"without a publishedversioncan yield distinctFootypes when downstream consumers resolvefoofrom crates.io; specify{ path = "../foo", version = "..." }for published workspaces. - Compile-time overrides: Set
[profile.dev.package.<slow-dep>] opt-level = 3(oropt-level = 3on heavy proc-macro/crypto deps) to keep debug test builds fast.
Clippy Discipline
Run cargo clippy --all-targets --all-features -- -D warnings on every commit. Configure workspace lints in Cargo.toml with negative priorities on lint groups (priority = -1) so individual lints override them, and use #[expect(clippy::lint)] (not #[allow]) as the standard for lint suppression. See references/clippy-config.md.
Performance Mindset
Benchmark with --release, profile with samply or cargo flamegraph, and avoid premature .collect() or stack-allocating large buffers before boxing (vec![0u8; N].into_boxed_slice()). Watch monomorphization budgets (extract non-generic inner functions) and false sharing (#[repr(align(64))] or align(128) on Apple Silicon, or crossbeam::utils::CachePadded). Benchmark with criterion — save baselines (--save-baseline main), use std::hint::black_box (with as_ptr() for pointer inputs), and isolate setup in iter_batched. See references/performance.md.
Generics and Dispatch
Use static dispatch (impl Trait / <T: Trait>) by default; switch to dyn Trait for heterogeneous collections or compile-time boundaries. In Edition 2024, -> impl Trait captures all in-scope lifetimes by default — use + use<'a, T> for precise capture. Prefer native async fn in traits over async-trait for static dispatch. See references/generics-dispatch.md.
Documentation & API Design
Document public items with # Examples, # Errors, # Panics, and # Safety, remember cargo nextest skips doctests (cargo test --doc), and use #[diagnostic::on_unimplemented] (Rust 1.78+) on complex public traits. See references/documentation.md.
Follow the four API principles (unsurprising, flexible, obvious, constrained), guard against hidden contracts (re-exported foreign types, silent !Send auto-trait regressions checked with is_normal<T>()), ship blanket impls (&T, &mut T, Box<T>) early, keep traits dyn-compatible where needed, and expose explicit close()/shutdown() for fallible or async cleanup. See references/api-design.md.
Async APIs
async fn lowers to a state machine returning an anonymous impl Future. Lock down the Send-ness contract on public APIs with -> impl Future<...> + Send + '_ — auto-trait propagation through -> impl Trait is silent and a single Rc<...> or std::sync::MutexGuard held across .await downgrades the whole future to !Send. Add + 'static only when the future must be spawned onto a multi-threaded executor. Drop equals cancel: document cancel-safety on every public async fn (recv vs read_exact/write_all). Use std::pin::pin! for stack-pinned local futures; Box::pin only when heap allocation is needed.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

