agentleFS
89jobrien89jobrien/godmode/skills/rust-conventions/SKILL.md

godmode:rust-conventions

Skill1 starsChanged 56 days agoMITView on GitHub

Rust coding conventions and best practices for all *.rs files in this workspace. Reference when writing new Rust code, reviewing a PR, or deciding between implementation approaches. Covers naming, ownership, error handling, API design, testing, and project organisation — based on the Rust API Guidelines, RFC 430, and idiomatic community standards.

The file

Show its rules and text

We split this skill into the rules it gives an agent

41 rules. About 0 are common, 10 are distinctive, and 31 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈10

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 31

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Follow RFC 430 naming conventions throughout:

    line 21
  2. Very specific:

    Prefer &T over cloning unless ownership transfer is required.

    line 36
  3. Very specific:

    Use &mut T when you need to mutate borrowed data.

    line 37
  4. Distinctive:

    Prefer borrowing and zero-copy operations to avoid unnecessary allocations.

    line 42
  5. Very specific:

    Use &str instead of String for function parameters when ownership is not required.

    line 43
  6. Very specific:

    Use Result<T, E> for all recoverable errors.

    line 49
  7. Very specific:

    Use the ? operator for error propagation.

    line 51
  8. Very specific:

    Create custom error types with thiserror.

    line 53
  9. Very specific:

    Use Option<T> for values that may legitimately be absent.

    line 55
  10. Distinctive:

    Use iterators instead of index-based loops — they are often faster, safer, and more expressive.

    line 80
  11. Very specific:

    Avoid premature .collect() — keep iterator chains lazy until a collection is actually needed.

    line 82
  12. Very specific:

    Prefer .filter_map() over .filter().map() when the two operations can be combined.

    line 84
  13. Very specific:

    Use .fold() for accumulation rather than a mutable variable outside the loop.

    line 85
  14. Very specific:

    Modules and visibility: Use mod + pub to encapsulate logic.

    line 91
  15. Very specific:

    Enums over flags: Prefer enum variants over bool parameters or integer flags.

    line 93
  16. Distinctive:

    Builders for complex construction: Use the builder pattern when a struct has more than 3–4 optional fields.

    line 95
  17. Very specific:

    Data parallelism: Use rayon for CPU-bound parallel iteration.

    line 101
  18. Very specific:

    Binary/library split: Keep main.rs thin — move all logic into lib.rs and its modules.

    line 102
  19. Very specific:

    Newtypes: Use newtypes to distinguish values that share the same primitive type (struct UserId(u64) vs struct OrderId(u64)).

    line 148
  20. Distinctive:

    Sealed traits: Use the sealed trait pattern to prevent downstream implementations of traits not intended for extension.

    line 152
  21. Very specific:

    Deref/DerefMut: Only smart pointers should implement these.

    line 155
  22. Very specific:

    Argument types: Prefer specific types over generic bool parameters.

    line 157
  23. Very specific:

    Use tokio as the async runtime.

    line 164
  24. Very specific:

    Never call .block_on() inside an async context.

    line 165
  25. Very specific:

    Use tokio::spawn for background tasks.

    line 166
  26. Very specific:

    Prefer tokio::fs over std::fs in async code.

    line 167
  27. Very specific:

    Keep async boundaries at the edges — pure computation should be synchronous.

    line 168
  28. Very specific:

    Run rustfmt (taskit check fmt) before every commit.

    line 174
  29. Very specific:

    Run taskit check lint and fix all warnings.

    line 175
  30. Distinctive:

    Keep lines at or under 100 characters.

    line 176
  31. Very specific:

    Place doc comments (///) immediately above the item they document.

    line 177
  32. Very specific:

    Use //! for module-level documentation.

    line 178
  33. Distinctive:

    Document error conditions, panic scenarios, and safety considerations.

    line 179
  34. Very specific:

    Write unit tests in #[cfg(test)] modules in the same file as the code under test.

    line 185
  35. Very specific:

    Write integration tests in tests/ with descriptive file names.

    line 186
  36. Very specific:

    Use taskit test run (preferred over taskit test run) for test filtering and parallelism.

    line 187
  37. Distinctive:

    Test edge cases explicitly — not just the happy path.

    line 188
  38. Very specific:

    Use semantic versioning in Cargo.toml.

    line 211
  39. Distinctive:

    Use feature flags for optional functionality.

    line 213
  40. Very specific:

    Keep main.rs and lib.rs minimal — move logic to named modules.

    line 214
  41. Distinctive:

    Before submitting any Rust code:

    line 222

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Rust Conventions

Apply these rules to all Rust code written in this workspace. Prioritise readability, safety, and maintainability in that order.


Naming (RFC 430)

Follow RFC 430 naming conventions throughout:

ItemConventionExample
Types, traits, enumsUpperCamelCaseTaskGraph, PolicyAction
Functions, methods, variablessnake_casecheck_tool, max_calls
Constants, staticsSCREAMING_SNAKE_CASEMAX_NODES, DEFAULT_TIMEOUT
Modulessnake_casemod graph_store
Lifetimesshort lowercase'a, 'src
Type parametersshort UpperCamelCaseT, E, Fut

Ownership and Borrowing

  • Prefer &T over cloning unless ownership transfer is required.
  • Use &mut T when you need to mutate borrowed data.
  • Annotate lifetimes explicitly when the compiler cannot infer them.
  • Rc<T> for single-threaded reference counting; Arc<T> for multi-threaded.
  • RefCell<T> for interior mutability in single-threaded contexts; Mutex<T> or RwLock<T> for multi-threaded.
  • Prefer borrowing and zero-copy operations to avoid unnecessary allocations.
  • Use &str instead of String for function parameters when ownership is not required.

Error Handling

  • Use Result<T, E> for all recoverable errors. Never unwrap() or expect() in library code — return Result instead.
  • Use the ? operator for error propagation. Avoid unwrap() unless in a test or a context where panic is explicitly acceptable.
  • Create custom error types with thiserror; use anyhow for application-level error aggregation.
  • Use Option<T> for values that may legitimately be absent.
  • Provide meaningful error messages with context. Error types must implement Debug and Display at minimum.
  • Validate function arguments and return appropriate errors for invalid input.
  • panic! is only for unrecoverable programmer errors (broken invariants). Never panic in response to external input.
// Prefer
fn load(path: &str) -> anyhow::Result<Config> {
    let text = std::fs::read_to_string(path)?;
    Ok(serde_json::from_str(&text)?)
}

// Avoid
fn load(path: &str) -> Config {
    let text = std::fs::read_to_string(path).unwrap(); // panics on missing file
    serde_json::from_str(&text).unwrap()
}

Iterators and Collections

  • Use iterators instead of index-based loops — they are often faster, safer, and more expressive.
  • Avoid premature .collect() — keep iterator chains lazy until a collection is actually needed.
  • Prefer .filter_map() over .filter().map() when the two operations can be combined.
  • Use .fold() for accumulation rather than a mutable variable outside the loop.

Patterns to Follow

  • Modules and visibility: Use mod + pub to encapsulate logic. Keep internal types private; expose only what callers need.
  • Enums over flags: Prefer enum variants over bool parameters or integer flags. Type safety catches misuse at compile time.
  • Builders for complex construction: Use the builder pattern when a struct has more than 3–4 optional fields.
  • Trait abstraction: Implement traits to abstract services and external dependencies, making them replaceable in tests.
  • Async: Structure async code with async/await and tokio. Avoid blocking in async contexts.
  • Data parallelism: Use rayon for CPU-bound parallel iteration.
  • Binary/library split: Keep main.rs thin — move all logic into lib.rs and its modules. This enables integration tests and downstream crate reuse.

Patterns to Avoid

  • unwrap() / expect() in non-test, non-prototype code.
  • Panics in library code.
  • Global mutable state — use dependency injection or thread-safe containers.
  • Deeply nested if/match blocks — extract functions or use combinators.
  • Ignoring compiler warnings — treat -D warnings as the standard in CI.
  • unsafe without necessity and thorough documentation.
  • Overusing .clone() where a borrow would suffice.
  • Unnecessary heap allocations in hot paths.

Common Traits

Eagerly derive or implement these where appropriate:

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MyType { ... }
TraitWhen
DebugEvery public type — required
CloneWhen callers need owned copies
PartialEq, EqFor value comparison and use in collections
HashWhen used as a HashMap/HashSet key
DefaultWhen a zero-value construction is meaningful
DisplayFor user-facing output
From / IntoFor idiomatic type conversions
AsRef, AsMutFor generic borrowing interfaces
FromIterator, ExtendFor collection types

Send and Sync are auto-implemented by the compiler. Avoid manual unsafe impl Send/Sync unless you fully understand the invariants.


API Design

  • Newtypes: Use newtypes to distinguish values that share the same primitive type (struct UserId(u64) vs struct OrderId(u64)).
  • Private fields: Structs should have private fields by default. Expose state through methods to preserve invariants.
  • Sealed traits: Use the sealed trait pattern to prevent downstream implementations of traits not intended for extension.
  • Method receivers: Functions with a clear receiver should be methods, not free functions.
  • Deref/DerefMut: Only smart pointers should implement these. Do not implement Deref to gain method inheritance.
  • Argument types: Prefer specific types over generic bool parameters. A bool argument at a call site conveys no intent (create(true) vs create(CreateMode::Overwrite)).

Async

  • Use tokio as the async runtime. Do not mix runtimes.
  • Never call .block_on() inside an async context.
  • Use tokio::spawn for background tasks; propagate JoinHandle errors.
  • Prefer tokio::fs over std::fs in async code.
  • Keep async boundaries at the edges — pure computation should be synchronous.

Code Style

  • Run rustfmt (taskit check fmt) before every commit.
  • Run taskit check lint and fix all warnings.
  • Keep lines at or under 100 characters.
  • Place doc comments (///) immediately above the item they document.
  • Use //! for module-level documentation.
  • Document error conditions, panic scenarios, and safety considerations.

Testing

  • Write unit tests in #[cfg(test)] modules in the same file as the code under test.
  • Write integration tests in tests/ with descriptive file names.
  • Use taskit test run (preferred over taskit test run) for test filtering and parallelism.
  • Test edge cases explicitly — not just the happy path.
  • Examples in doc comments must compile and use ?, not unwrap().
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_tool_denies_blocked() {
        let policy = GovernancePolicy {
            blocked_tools: vec!["shell_exec".into()],
            ..Default::default()
        };
        assert_eq!(policy.check_tool("shell_exec"), PolicyAction::Deny);
    }
}

Project Organisation

  • Use semantic versioning in Cargo.toml.
  • Include description, license, repository, keywords, categories in every crate.
  • Use feature flags for optional functionality.
  • Keep main.rs and lib.rs minimal — move logic to named modules.
  • Organise modules as mod.rs directory layout (src/foo/mod.rs) rather than flat files (src/foo.rs). This is the preferred convention in this workspace.

Quality Checklist

Before submitting any Rust code:

  • Naming follows RFC 430 throughout
  • All public types derive or implement Debug
  • Error handling uses Result<T, E> — no bare unwrap() in non-test code
  • All public items have /// rustdoc with at least one sentence
  • Tests cover the happy path and at least one failure/edge case
  • No unsafe without a // SAFETY: comment explaining the invariant
  • taskit check fmt — no format diff
  • taskit check lint — zero warnings
  • taskit test run — all green

Related

  • skills/agent-governance/SKILL.md — Rust implementations of governance patterns
  • skills/systematic-debugging/SKILL.md — debugging approach for Rust-specific issues
  • skills/verification-before-completion/SKILL.md — CI gate checklist

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.