rust-conventions
Skill7 starsChanged 3 days agoMITView on GitHub
Rust projects: crate choices (clap, tokio, tracing, mockall) and layout. TRIGGER when: editing `.rs` files; touching `Cargo.toml`, `Cargo.lock` or `.cargo/config.toml`; adding a Rust dependency; setting up a Rust CLI, server, async trait, mock or subscriber; a `cargo run`/`cargo test` needing env vars. SKIP when: no Rust is involved. Load `rust-http-conventions` alongside for HTTP, `rust-build-conventions` for the toolchain pin, sqlx tests, `build.rs`, cargo-chef and coverage.
5 other projects use a version of this.
Adopted by
Most recently taken up by
- leroyguillaume/claudeword for word, first seen Nov 29, 2026
- static-web-server/static-web-servertheir own version, first seen Nov 9, 2026
- vivienm/skillstheir own version, first seen Oct 17, 2026
- flntfnd/claude-skillstheir own version, first seen Aug 20, 2026
- fielding/skillstheir own version, first seen Jul 2, 2026
Other versions5 projects use a version of this.
Word for word · 1
- leroyguillaume/claude★ 7100% same
Edited · 0
None found.
Wrote their own version · 4
- static-web-server/static-web-server★ 2.4ksame name
- fielding/skills★ 1same name
- flntfnd/claude-skills★ 0same name
- vivienm/skills★ 0same name
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 repository54 other files it gives its agents.
- adr-conventionsSkill
- api-conventionsSkill
- architecture-conventionsSkill
- argocd-conventionsSkill
- ci-conventionsSkill
- config-conventionsSkill
- contributing-conventionsSkill
- councilSkill
- cryptography-conventionsSkill
- dependency-update-conventionsSkill
- diagram-conventionsSkill
- docker-conventionsSkill
- documentation-conventionsSkill
- frontend-conventionsSkill
- github-actions-conventionsSkill
- github-issue-conventionsSkill
- github-pr-conventionsSkill
- github-repo-settingsSkill
- gitlab-ci-conventionsSkill
- helm-conventionsSkill
- herdr-core-delegationSkill
- herdr-delegationSkill
- herdr-tui-delegationSkill
- kopf-conventionsSkill
- kubernetes-operator-conventionsSkill
- logging-conventionsSkill
- logo-conventionsSkill
- mise-conventionsSkill
- ollama-conventionsSkill
- openssf-conventionsSkill
- pr-conventionsSkill
- pre-commit-conventionsSkill
- project-metadata-conventionsSkill
- python-async-conventionsSkill
- python-conventionsSkill
- readme-conventionsSkill
- release-script-conventionsSkill
- release-supply-chain-conventionsSkill
- renovate-ci-conventionsSkill
- rest-conventionsSkill
- rust-build-conventionsSkill
- rust-http-conventionsSkill
- security-policy-conventionsSkill
- signal-handling-conventionsSkill
- sql-conventionsSkill
- starlight-conventionsSkill
- systemd-conventionsSkill
- system-user-conventionsSkill
- task-conventionsSkill
- terraform-conventionsSkill
- topic-splittingSkill
- ui-copy-conventionsSkill
- web-layout-conventionsSkill
- yaml-conventionsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
17 rules. 0 are common, 0 are distinctive, and 17 are very specific to this project.
0
Common
Most of the 4 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
17
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Prefer static dispatch over dynamic dispatch.
- Very specific: line 23
Prefer argument-position impl Trait over a named generic parameter when the parameter's type is used only once and never needs to be named.
- Very specific: line 27
Keep the named generic only when the type must actually be referred to: it is used in more than one place, you need it via turbofish …
- Very specific: line 50
Prefer default_value_t = <typed value> over a stringly-typed default_value = "..." whenever the field's type is anything other than a …
- Very specific: line 98
Use tokio as the async runtime.
- Very specific: line 122
Always set up structured logging/tracing with tracing and tracing-subscriber.
- Very specific: line 182
Add local cargo fmt --check and cargo clippy hooks to .pre-commit-config.yaml.
- Very specific: line 225
Use mockall for test doubles.
- Very specific: line 244
Never default to Box<dyn Trait> / &dyn Trait when generics or impl Trait express the same thing with static dispatch.
- Very specific: line 246
Never use an async runtime other than tokio (async-std, smol, …).
- Very specific: line 247
Never set force = true in a .cargo/config.toml [env] table, and never put a credential there that reaches anything beyond the project's own …
- Very specific: line 250
Never front a documented cargo run / cargo test with a wall of VAR=value assignments when .cargo/config.toml can carry them.
- Very specific: line 252
Never use println! / eprintln!
- Very specific: line 254
Never add a clap option without an env = "..." attribute, and never build the EnvFilter from EnvFilter::from_env / from_default_env or a …
- Very specific: line 258
Never leave clippy warnings unaddressed.
- Very specific: line 260
Never hand-roll mock structs, fakes, or stubs for a trait when mockall can generate them, and never pull in another mocking crate (mockers, …
- Very specific: line 263
Never reach for the async-trait crate.
“Common” is measured: kept by at least 6 in 10 of the 4 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 conventions
Always:
- Prefer static dispatch over dynamic dispatch. Use generics with trait
bounds or
impl Traitrather thanBox<dyn Trait>/&dyn Trait. Reach for trait objects only when static dispatch is genuinely impossible (e.g. heterogeneous collections, recursive types, or a hard binary-size constraint), and leave a one-line comment explaining why. - Prefer argument-position
impl Traitover a named generic parameter when the parameter's type is used only once and never needs to be named. Writefn run(handler: impl Handler), notfn run<H: Handler>(handler: H)/fn run<H>(handler: H) where H: Handler. Keep the named generic only when the type must actually be referred to: it is used in more than one place, you need it via turbofish (foo::<H>()), you reference its associated types (H::Item), it appears in the return type, or the function is a trait-impl method whose signature must match the trait declaration. The named form is strictly more verbose for the single-use case, so default toimpl Traitthere. - Lay out modules with the
<module>.rs+<module>/directory form, not<module>/mod.rs. A module that has children lives infoo.rsalongside afoo/directory holding its submodules (foo/bar.rs), never infoo/mod.rs. Themod.rsstyle is discouraged: it scatters many identically named files across the tree and makes editor tabs ambiguous. An existingmod.rslayout is migrated only on request or as a change of its own, never as a drive-by inside unrelated work. - In a Cargo workspace, put each member crate in its own directory at the
repository root (
<repo>/<crate-name>/), not nested under acrates/(orpackages/,libs/, …) subdirectory. List members explicitly in the root[workspace] members = [...]rather than globbing a wrapper dir. The rootCargo.tomlis a virtual manifest ([workspace]only, no[package]). An existingcrates/-style layout is flattened only on request or as a change of its own. - Build CLIs with
clap(derive API), giving every argument anenv = "..."attribute. Precedence and variable names followconfig-conventions. - Prefer
default_value_t = <typed value>over a stringly-typeddefault_value = "..."whenever the field's type is anything other than aString/&str— enums, integers, paths, durations, etc.default_value_ttakes a real value of the field's type (compile-time checked, rendered viaDisplay), so the default cannot drift out of sync with the type and a typo is a build error rather than a runtime parse failure. (A plainStringflag may keepdefault_value = "info".) An enum derivingclap::ValueEnumand markedvalue_enumneeds nothing more:#[arg(long, env = "...", value_enum, default_value_t = Mode::Auto)]. Any other custom type used as a default needs aDisplayimpl mirroring itsFromStr. - Give the development defaults a
.cargo/config.tomlwith an[env]table, committed at the repository root, as soon as a binary needs an environment variable to start.cargo runandcargo testthen work from a fresh clone with nothing exported, and theDATABASE_URL=… JWT_SECRET=… S3_BUCKET=… cargo runincantation disappears fromCONTRIBUTING.mdinstead of being copy-pasted wrong.
Five rules keep it from becoming a liability:# .cargo/config.toml # Cargo sets these only for what it spawns (`cargo run`, `cargo test`), not # for ./target/debug/app run by hand or in a container. [env] DATABASE_URL = "postgres://app:app@localhost:5432/app" # Resolved against this file's parent directory, not the shell's cwd. MIGRATIONS_DIR = { value = "migrations", relative = true }- Never
force = true. Without it, a variable already present in the environment wins and the file stays a fallback; with it, CI's ownDATABASE_URLand a container's real configuration are silently replaced by a development default. That single word is the difference between a convenience and a footgun. - Never a value the project's config file sets.
[env]reaches the binary as environment variables, which beat the config file (config-conventions): a default here silently overrides what a contributor wrote there. - Only values that unlock the project's own throwaway stack — the
docker-composeservices and nothing else. A credential that reaches a shared or production system never goes in a committed file, whatever the variable is called. - Say in a comment that Cargo applies
[env]only to processes it spawns.cargo runandcargo testget the values; running./target/debug/appby hand, or the binary in a container, gets nothing. That is the first surprise, and it is cheaper to answer in the file than in a bug report. - Keep it the one home for those values.
CONTRIBUTING.mdsays the file exists and that the environment takes precedence; it does not restate the values.
- Never
- Use
tokioas the async runtime. - In a long-running process, apply
signal-handling-conventions. Rust mechanics: enable tokio'ssignalfeature and write oneshutdown_signal()future that completes onSIGTERMorSIGINT, then drive shutdown from it:
Handle both viaasync fn shutdown_signal() { use tokio::signal::unix::{signal, SignalKind}; let mut interrupt = signal(SignalKind::interrupt()).expect("SIGINT handler"); let mut terminate = signal(SignalKind::terminate()).expect("SIGTERM handler"); tokio::select! { _ = interrupt.recv() => {}, _ = terminate.recv() => {} } }SignalKind(don't mixctrl_c()in forSIGINT— keep the two consistent). The above is unix-only, which is the right default for a Linux-container target; only if the binary must also run on Windows, guard it with#[cfg(unix)]and fall back totokio::signal::ctrl_c()under#[cfg(not(unix))]. A server hands it to its graceful-shutdown hook (seerust-http-conventions); a worker loop races it withtokio::select!.tokio::signal::ctrl_calone is not enough — it only coversSIGINT, so a container stopped withSIGTERMwould never drain. - Any HTTP surface — framework, OpenAPI, input validation with
validator— followsrust-http-conventions; load it before touching a handler, a router or a request/response DTO. - Always set up structured logging/tracing with
tracingandtracing-subscriber. Initialise the subscriber once at the start ofmain, configured with anEnvFilter. The filter directive comes from aclapoption (--log-filter, its variable named perconfig-conventions), never read directly from the environment — which also rules outRUST_LOG, read by other crates' ownfrom_default_env()machinery. Document the directive syntax in the option's help so--helpis self-sufficient. The log format is aclapoption too (logging-conventions).tracing_subscriber::fmt()writes to stdout by default, which mixes logs into the program's result, so always point it at stderr. Example:use clap::Parser; #[derive(Clone, Copy, clap::ValueEnum)] enum LogFormat { Text, Json } #[derive(clap::Parser)] struct Cli { /// `tracing` filter directive (e.g. `info`, `myapp=debug,axum=warn`) /// /// Syntax: <https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives> #[arg(long = "log-filter", env = "MYTOOL_LOG_FILTER", default_value = "info")] log_filter: String, #[arg(long, env = "MYTOOL_LOG_FORMAT", value_enum, default_value_t = LogFormat::Text)] log_format: LogFormat, } fn main() -> Result<(), tracing_subscriber::filter::ParseError> { let cli = Cli::parse(); // `EnvFilter::new` silently drops a directive it cannot parse. let fmt = tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::try_new(&cli.log_filter)?) .with_writer(std::io::stderr); match cli.log_format { LogFormat::Text => fmt.init(), LogFormat::Json => fmt.json().init(), // needs the `json` feature } Ok(()) } - Apply
logging-conventions. Rust mechanics:debug!(andtrace!for very high-volume detail) viatracing, level controlled by theclap-parsed filter above, structured fields (debug!(%name, count, "…")) — never string interpolation, neverprintln!/eprintln!for diagnostics. Only the program's result goes to stdout; everything else goes to stderr.
println!is for what the program produces — the thing a caller would pipe into a file or another command. Error messages, usage hints and notes to whoever is watching go toeprintln!, so thatcmd > out.txtkeeps the output clean and the diagnostics visible. The split is by audience, not by severity: stdout is for the next program in the pipeline, stderr is for the person at the terminal.This does not loosen the logging rule. The line is between what a CLI says to its user — results on stdout, a final error message on stderr before it exits non-zero — and diagnostics about the program's own workings, which go through
tracing(writing to stderr, as above), never through either macro.- Format with
rustfmtand lint withclippy(cargo clippy -- -D warnings). Add localcargo fmt --checkandcargo clippyhooks to.pre-commit-config.yaml. - Declare lints once, in the manifest — never as
#![warn(...)]attributes scattered across crate roots. In a workspace, the table lives in the root virtual manifest and every member opts in with[lints] workspace = true:# Cargo.toml (workspace root) [workspace.lints.rust] unsafe_code = "forbid" [workspace.lints.clippy] all = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 }
Lint groups must carry# <crate>/Cargo.toml [lints] workspace = truepriority = -1. Cargo turns each entry into a rustc flag and rustc applies "last flag wins", but Cargo ignores the order the entries are written in and sorts bypriorityinstead. A group left at the default priority of 0 can therefore be emitted after an individualallowof one of its lints and silently re-enable it.clippy::allincludeslint_groups_priority, which catches this and suggests the fix — do not ignore that warning. - No
missing_docs. It demands a///on every public item, which ends up paraphrasing signatures. Whenpedanticasks for# Errorsor# Panics, write only what the signature cannot say: which input fails, and how. - Aim for an empty allow-list.
pedanticis worth keeping on: its noisy lints still force a decision, and its cast/float lints catch real bugs long after the code was written. When a lint fires, the default is to comply. Blanketallowentries in the manifest are a last resort and must carry a comment explaining what was traded away — a globalallowhides a problem everywhere, whereas a scoped#[allow(clippy::…)]at the offending item, with a justification comment, documents it exactly where it matters. Prefer the scoped form every time. Beware of writing the allow-list before the code: allows added at bootstrap "because everyone disables those" are cargo-cult, and some will not even be in the group any more. - Toolchain pin (in
mise.toml),sqlxdatabase tests,build.rsforsqlx::migrate!,cargo-chefDocker builds and test coverage live inrust-build-conventions; load it alongside for those. - Use
mockallfor test doubles. Define collaborators as traits, annotate them with#[cfg_attr(test, mockall::automock)](ormock!when you cannot own the trait), and inject the mock in unit tests. Keep production injection on static dispatch (generics /impl Trait); only the test wiring of a synchronous trait may fall back to a trait object if generics make the seam impractical (async traits are not object-safe, see below). Addmockallunder[dev-dependencies]viacargo add --dev mockall.mockallsupports native async traits (Rust ≥ 1.75), so there is no need forasync-traitto make a trait mockable — keep#[cfg_attr(test, mockall::automock)]above the trait definition. - For async methods on a trait, use a native
async fnor, when the returned future must beSend(e.g. it crosses atokio::spawnor a controller runtime), the desugared formfn f(&self, …) -> impl Future<Output = …> + Send. Such traits are not object-safe, which is fine: inject them with generics (T: Trait), notdyn Trait, consistent with the static-dispatch rule above.
Never:
- Never default to
Box<dyn Trait>/&dyn Traitwhen generics orimpl Traitexpress the same thing with static dispatch. - Never use an async runtime other than
tokio(async-std,smol, …). - Never set
force = truein a.cargo/config.toml[env]table, and never put a credential there that reaches anything beyond the project's own development stack. Development defaults must lose to a real environment. - Never front a documented
cargo run/cargo testwith a wall ofVAR=valueassignments when.cargo/config.tomlcan carry them. - Never use
println!/eprintln!(or ad-hoclogsetup) for application diagnostics; route everything throughtracing. - Never add a
clapoption without anenv = "..."attribute, and never build theEnvFilterfromEnvFilter::from_env/from_default_envor a directstd::envread — the directive must flow through theclap-parsed value. - Never leave
clippywarnings unaddressed. If a lint must be allowed, add a scoped#[allow(...)]with a justification comment. - Never hand-roll mock structs, fakes, or stubs for a trait when
mockallcan generate them, and never pull in another mocking crate (mockers,faux, …) whenmockallfits. - Never reach for the
async-traitcrate. Use nativeasync fn/-> impl Future<Output = …> (+ Send)in traits and generic injection instead. The only exception is an external trait you do not own that is itself defined with#[async_trait].
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.

