Skip to content
Development
Skill

/rust-rules

Rust coding rules: style, patterns, security, testing. Triggers: .rs, Cargo.toml, Cargo.lock, Tokio, Axum, Serde, clippy, cargo test.

From plugin
ai-toolkit
161111 skills44 agents
Install
$ npx -y skills add softspark/ai-toolkit --skill rust-rules --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/rust-rules

Context preview

The summary Claude sees to decide when to auto-load this skill.

Rust coding rules: style, patterns, security, testing. Triggers: .rs, Cargo.toml, Cargo.lock, Tokio, Axum, Serde, clippy, cargo test.

SKILL.md

rust-rules.SKILL.md
name: rust-rules
description: "Rust coding rules: style, patterns, security, testing. Triggers: .rs, Cargo.toml, Cargo.lock, Tokio, Axum, Serde, clippy, cargo test."
effort: medium
user-invocable: false
allowed-tools: Read

Rust Rules

These rules come from `app/rules/rust/` in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Rust. Apply them when writing or reviewing Rust code.

Rust Coding Style

Naming

  • snake_case: functions, methods, variables, modules, crates.
  • PascalCase: types, traits, enums, structs, type parameters.
  • SCREAMING_SNAKE: constants and statics.
  • Short lifetimes: `'a`, `'b`. Descriptive only when multiple coexist: `'input`, `'output`.
  • Crate names: kebab-case in Cargo.toml, snake_case in code.

Ownership

  • Borrow (`&T`) when you only need to read. Own (`T`) when storing or consuming.
  • Use `&str` over `String` in function parameters when possible.
  • Use `Cow<'_, str>` when you sometimes need to allocate.
  • Avoid `.clone()` as a first resort -- restructure ownership instead.
  • Use `Arc<T>` only when shared ownership across threads is required.

Types

  • Use newtypes for domain primitives: `struct UserId(Uuid)`.
  • Use `#[derive(Debug, Clone, PartialEq)]` on data types.
  • Implement `Display` for user-facing output, `Debug` for developer output.
  • Use `#[non_exhaustive]` on public enums and structs for future compatibility.
  • Prefer enums over boolean flags for state representation.

Functions

  • Return `Result<T, E>` for operations that can fail. Avoid panicking.
  • Use `impl Trait` in argument position for flexibility, return position for simplicity.
  • Use `where` clauses for complex bounds instead of inline.
  • Prefer iterators over index-based loops.
  • Use `let-else` (1.65+) for early-exit pattern matching.

Modules

  • Use `mod.rs` or filename-based modules. Be consistent within the project.
  • Re-export public API from `lib.rs` for a clean surface.
  • Keep modules focused. One major type or concept per module.
  • Use `pub(crate)` for internal-only visibility.

Formatting

  • Use `rustfmt` with default settings. Do not fight the formatter.
  • Use `clippy` with `-D warnings` in CI. Fix all warnings.
  • Set MSRV (Minimum Supported Rust Version) in `Cargo.toml`.

Cargo

  • Use workspace dependencies to unify versions across crates.
  • Use feature flags for optional functionality.
  • Set `edition = "2021"` (or latest stable edition).
  • Use `[profile.release]` with `lto = true` and `codegen-units = 1` for production.

Rust Frameworks

Axum

  • Use extractors for typed request parsing: `Path`, `Query`, `Json`, `State`.
  • Use `Router::new().route("/path", get(handler))` for route definitions.
  • Share state via `State(Arc<AppState>)` extractor.
  • Implement `IntoResponse` on error types for clean error handling.
  • Use Tower middleware layers for auth, logging, tracing, rate limiting.

Actix-web

  • Use extractors: `web::Path`, `web::Json`, `web::Data`.
  • Use `App::new().service()` for route configuration.
  • Share state with `web::Data<Arc<State>>`.
  • Use `actix-web::middleware` for logging and error handling.

Tokio

  • Use `#[tokio::main]` for the entry point. Use `tokio::spawn` for tasks.
  • Use `tokio::select!` for waiting on multiple futures.
  • Use `tokio::time::timeout()` for operation deadlines.
  • Use `tokio::sync::broadcast` for pub/sub, `mpsc` for work queues.
  • Use `tokio::task::spawn_blocking()` for CPU-intensive work in async context.

SQLx

  • Use compile-time checked queries: `sqlx::query_as!(User, "SELECT ...")`.
  • Use `PgPool` for connection pooling. Pass as shared state.
  • Use migrations: `sqlx migrate add` and `sqlx migrate run`.
  • Use `sqlx::FromRow` derive for automatic struct mapping.
  • Set `DATABASE_URL` for compile-time query verification.

Serde

  • Use `#[derive(Serialize, Deserialize)]` on all DTOs.
  • Use `#[serde(rename_all = "camelCase")]` for JSON API compatibility.
  • Use `#[serde(deny_unknown_fields)]` for strict deserialization.
  • Use `#[serde(default)]` for optional fields with defaults.
  • Use `#[serde(skip_serializing_if = "Option::is_none")]` for clean output.

Clap

  • Use `#[derive(Parser)]` for CLI argument parsing.
  • Use subcommands with enum variants: `#[derive(Subcommand)]`.
  • Use `#[arg(env = "VAR_NAME")]` for env var fallback.
  • Use `value_parser` for custom validation of arguments.

Tracing

  • Use `tracing` crate over `log` for structured, async-aware logging.
  • Use `#[instrument]` attribute on functions for automatic span creation.
  • Use `tracing_subscriber` with `EnvFilter` for runtime log level control.
  • Add `trace_id` to all log entries for distributed tracing correlation.

Testing Crates

  • `mockall`: auto-generate mocks from traits.
  • `wiremock`: HTTP mock server for integration tests.
  • `testcontainers`: Docker containers for database tests.
  • `proptest` / `quickcheck`: property-based testing.

Rust Patterns

Error Handling

  • Use `thiserror` for library error types (structured, typed enums).
  • Use `anyhow` for application/binary code (flexible, context-rich).
  • Wrap errors with context: `.with_context(|| format!("loading {path}"))?`.
  • Use `#[from]` attribute for automatic error conversion in thiserror enums.
  • Map domain errors to HTTP/gRPC errors at API boundaries only.

Builder Pattern

  • Use builder for structs with many optional fields.
  • Return `Result` from `build()` when validation is needed.
  • Use `#[derive(Default)]` + `TypedBuilder` derive macro for compile-time safety.
  • Chain setter methods returning `Self` for ergonomic API.

Newtype Pattern

  • Wrap primitive types for type safety: `struct Email(String)`.
  • Validate in constructor: `Email::new(raw) -> Result<Self, ValidationError>`.
  • Implement `Deref` only when the inner type's full API is appropriate.
  • Use `#[repr(transparent)]` for zero-cost newtypes in FFI.

Trait Design

  • Keep traits small and focused. Compose with supertraits.
  • Use associated types f
Read more
Ships withai-toolkit

Professional-grade AI coding toolkit with multi-platform support. Machine-enforced safety, 109 skills, 44 agents, expanded lifecycle hooks, persona presets, experimental opt-in plugin packs, and benchmark tooling — works with Claude Code, Claude Chat/Cowork,

Get the whole plugin