Skip to content
Back to skills

Rust Idiomatic

ASecurity

Contracts. Use whenever creating or changing Rust structs, options, state enums, newtypes, traits, conversions, or choosing owned versus borrowed signatures and synchronization.

  • 2 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 15, 2026
developmentrustgoapi

Works with

  • api

Security analysis

A100/100

Pro scans all 4 files and shows the line behind each finding

Scanned November 27, 2026

npx -y skills add Dankosik/rust-service-template-rest --skill rust-idiomatic --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Rust Idiomatic?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Rust Idiomatic
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/dankosik-rust-idiomatic/badge)](https://www.skillsdirectory.com/skills/dankosik-rust-idiomatic)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: rust-idiomatic
description: "Contracts. Use whenever creating or changing Rust structs, options, state enums, newtypes, traits, conversions, or choosing owned versus borrowed signatures and synchronization."
---

# Rust Idiomatic

**Contracts.** Make ownership and caller expectations visible in ordinary Rust: admissible states, permitted transitions, mutation authority, and the meaning of absence or failure. Remember that a type enforces only its construction and transition invariants; freshness, durable completion, and external resource lifetimes require explicit runtime coordination.

**Sharing and parameters.** Separate long-lived state from transient call values before choosing ownership: give stored structs owned fields so lifetimes do not spread across containers, while giving per-call requests, queries, options, and write rows borrowed views (`&'a str`, `Cow<'a, str>`, `&'a [T]`, or `Borrow<T>`) when callers hold borrowed inputs across the call; see [ownership examples](references/ownership.md). Accept borrowed slices (`&str`, `&[T]`, `&Path`, `Option<&T>`) for read-only parameters and owned `T` by value when the callee always stores or consumes it. Keep concrete parameter types in application code unless real callers benefit from generic conversions.

**Mutation and completion.** Prefer plain `&mut self` over interior mutability—drop unnecessary `Rc<RefCell<T>>` or `Mutex` wrappers whenever callers own exclusive access, and when shared `&self` mutation is genuinely required, group coupled fields (such as state and its audit log) under one `Mutex<Inner>` rather than separate locks that can race. Prepare fallible work before committing via `mem::replace`/`mem::swap`, release mutex guards before dropping freed collections or notifying waiters, and bind cancel-safe rollback to `std::mem::DropGuard`; see [ownership examples](references/ownership.md). Remember struct fields drop in declaration order, require `Send`/`Sync`/`'static` only at thread crossings, and expose an explicit observed completion step whenever flushing or closing can fail or suspend.

**Representation.** Inspect the Cartesian product of `Option` and `bool` fields on any struct: whenever combinations are illegal or a field turns inert in one mode, move mode-specific fields into an `enum` variant, and bind any justified live projection or cache to its source owner, as shown in [representation examples](references/representation.md). Encode strictly positive bounds with `NonZero*`, wrap distinct IDs, generations, or units in newtypes, replace multi-`bool` or ambiguous boolean function parameters with small named enums, separate absent from empty only when the contract distinguishes them, and leave passive DTOs and independent single flags plain. Keep public workspace enums and structs exhaustive, reserving `#[non_exhaustive]` for crates with external semver consumers.

**Boundary invariants.** Parse and validate once at the owning boundary so downstream code accepts checked witness types instead of repeating `is_valid_*` checks, validating borrowed `&str`/`&[u8]` slices completely before allocating owned `String` or `Vec` fields in `FromStr`/`TryFrom` so malformed inputs waste zero heap allocations. Audit every construction and mutation path—`Deserialize`, `From`/`TryFrom`, `Default`, and field visibility—so invariant-bearing fields stay private behind read-only accessors while plain data stays direct, and omit `Default` when no neutral value exists. Put required arguments into `Builder::new(required)` instead of panicking in `build()`, reserving builders for multi-option construction and typestate for protocols whose compile-time safety outweighs its generic cost over an enum.

**Traits and API ergonomics.** Put trait bounds on `impl` blocks rather than `struct`/`enum` definitions (using `derive-where` when derives over-constrain generics), seal a trait only to protect a closed invariant rather than replacing `std::borrow::Borrow`, and keep primary behavior in inherent methods; see [API and trait examples](references/api-and-traits.md). Follow Rust naming contracts (`as_` O(1) borrow, `to_` allocating/computing, `into_` consuming, getters without `get_`, `len`/`is_empty`, `FromStr`), keep `Eq`/`Ord`/`Hash` consistent, implement `From`/`TryFrom`, never derive `Debug` on types holding credentials (redact secrets manually), and mark `#[must_use]` where ignoring a return loses a check. Use `const` assertions for `Send`/`Sync` bounds and Edition 2024 `use<..>` precise capturing when RPIT over-captures lifetimes.

**Collections and iterators.** Select collections by access pattern and observable order (`BTreeMap` orders by key; `IndexMap` preserves insertion order whenever callers, hashes, or diagnostics observe ordering), checking [workspace utility crates](../rust-dependencies/references/workspace-crates.md) before hand-rolling compact strings, inline vectors, LRU maps, enum-indexed tables, or boilerplate derives. Keep integer overflow and byte-versus-UTF-8 boundaries explicit, propagate fallible iterator results with `collect::<Result<_, _>>()`, and verify `filter`/`take` order, scoping changes strictly to touched code.

Files in this skill

  • LICENSE1 KB
  • SKILL.md4.7 KB
  • references/ownership.md1.7 KB
  • references/representation.md2.2 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.