Skip to content
Development
Skill

/rust-best-practices

Write idiomatic, robust, maintainable Rust. Use this skill whenever you write, review, refactor, debug, or explain Rust code: new crates, modules, functions, structs, traits, error types, async code, unsafe or FFI code, Cargo.toml, tests, or rustdoc. Trigger on any mention of

From plugin
beautiful-rust
2k3 skills

Claude Code

$ npx -y skills add morganlinton/BeautifulRust --skill rust-best-practices --agent claude-code

SKILL.md

rust-best-practices.SKILL.md
name: rust-best-practices
description: >-
  Write idiomatic, robust, maintainable Rust. Use this skill whenever you write, review,
  refactor, debug, or explain Rust code: new crates, modules, functions, structs, traits,
  error types, async code, unsafe or FFI code, Cargo.toml, tests, or rustdoc. Trigger on
  any mention of Rust, cargo, crates, .rs files, the borrow checker, lifetimes, traits,
  clippy, or rustfmt, even when the user does not ask for "best practices" or "idiomatic"
  code. Synthesized from the Google Rust Style Guide, the Rust API Guidelines,
  Effective Rust, Rust Design Patterns, and Microsoft's Pragmatic Rust Guidelines.

Rust best practices

Distilled from five Rust style and design guides, with a digest of each in `references/`. Where they disagree, this file says which to follow and why.

1. Mindset

  • **Write Rust-shaped code.** Don't port C++, Java, C#, or Python constructs one-to-one.

Model errors with `Result`, resources with ownership and `Drop`, polymorphism with traits and enums, and nullability with `Option`. Inheritance-flavored tricks (`Deref` to a "base" struct, `Manager`/`Factory` types, `throw_if_null` helpers) are smells.

  • **Make invalid states unrepresentable.** Push invariants into types: enums instead of

bool flags and "must be X if Y" comments, newtypes for units and IDs, fallible constructors that validate once. Then the compiler enforces what a comment only requests.

  • **Application code is not library code.** Library code (anything with external users)

follows the API-design rules below strictly. Application code should favor simplicity and directness: concrete types, `String` or `&str` rather than `impl Into<String>` parameters, `anyhow`-style errors, `Vec` return values, no speculative generality.

  • **Let the tools do the work.** rustfmt owns formatting, clippy owns idiom checks, the

compiler owns memory safety. Spend your attention on design.

2. Before you hand back code

Run these and fix everything they report:

cargo fmt
cargo clippy --all-targets --all-features -- -D warnings
cargo test
cargo doc --no-deps   # libraries: catches broken doc links and missing docs
  • Fix a lint rather than silencing it. When a lint is genuinely wrong for one item, use

`#[expect(clippy::name, reason = "...")]` on the narrowest item. `expect` warns when the lint stops firing, so stale suppressions get cleaned up. Use `#[allow]` only in generated code or macro output.

  • Never put `#![deny(warnings)]` in source: new toolchains add warnings and break the

build. Enforce warnings-as-errors in CI instead, with `cargo clippy -- -D warnings`.

  • Configure lints once in `Cargo.toml` (`[lints]` or `[workspace.lints]`), not with

scattered crate attributes. If a project has none, suggest `lints/lints.toml` and `lints/clippy.toml` from https://github.com/morganlinton/BeautifulRust; the suppression lints in it need `rust-version` 1.81 or later.

3. Ownership and borrowing

**Prefer unique ownership.** Reach for `Rc`/`Arc` only when shared ownership is part of the design, and for `RefCell`/`Mutex` only when interior mutability is. They are not failures, but they move checking from compile time to run time, so use them on purpose.

**Don't clone to make the borrow checker stop complaining.** A clone that exists only to end a borrow produces a silent copy whose later changes are lost. Try these first, in roughly this order:

1. Extend a temporary with a named `let`, or shorten a borrow with a block. 2. Split a long expression into typed intermediates so the failing step is visible. 3. Move a field out of `&mut self` with `std::mem::take` (needs `Default`), `std::mem::replace`, or `Option::take` instead of cloning it. 4. Split a large struct into smaller ones so disjoint fields can be borrowed separately. The compiler tracks disjoint field borrows inside one function, but not across method calls. 5. Clone small, immutable data deliberately, and say so in a comment if it's not obvious. 6. Use indices into an owning `Vec`, or `Rc<RefCell<_>>` with `Weak` back-pointers, as a last resort. Avoid self-referential structs.

// Move out of a &mut enum without cloning.
fn a_to_b(e: &mut MyEnum) {
    if let MyEnum::A { name, x: 0 } = e {
        *e = MyEnum::B { name: std::mem::take(name) };
    }
}

**Accept the most general borrowed type.** `&str` not `&String`, `&[T]` not `&Vec<T>`, `&T` not `&Box<T>`, `Option<&T>` not `&Option<T>`. Deref coercion then lets callers pass owned values, borrows, or literals. Where you only read a path, string, or byte buffer, `impl AsRef<Path>` / `impl AsRef<str>` / `impl AsRef<[u8]>` is fine on parameters (never on struct fields; store `PathBuf` and `String`). Library code that only iterates should take `impl IntoIterator<Item = T>`; application code may simply take `&[T]`.

**Take ownership only when you need it, and then take it by value.** If a function stores or consumes its argument, take `T`, not `&T` plus an internal `.clone()`. If it only reads, take `&T`; if it mutates in place, `&mut T`. Return multiple values as a tuple or struct, not through `&mut` out-parameters (reusing a caller-owned buffer, as `Read::read` does, is the exception).

**Prefer owned data in structs.** A struct holding `&'a T` forces a lifetime onto every container. Owning a `String` or `Vec<u8>` is usually simpler and rarely the bottleneck. When a type does carry a lifetime, give it a descriptive name (`'src`, `'conn`); `'_` and `'a` are fine on simple functions.

**Freeze after setup.** Build with `let mut`, then rebind `let data = data;` so later code cannot mutate it by accident.

**Keep `Rc`, `Arc`, `Box`, and `RefCell` out of public signatures.** Take `&T`, `&mut T`, or `T` and let callers decide how to own things. A service that must be shared implements a cheap `Clone` by wrapping its state in `Arc<Inner>` internally.

4. Types and API design

Naming

| Item | Case | No

Read more
@morganlinton
Ships withbeautiful-rust

Three standard Agent Skills and a lints config that teach coding agents to write, review, port, and enforce idiomatic Rust: rust-best-practices loads whenever an agent writes or changes Rust, and steers it toward idiomatic, robust, maintainable code.

Stars on GitHub

Momentum

stars in total
2.0k
Star history of morganlinton/BeautifulRust on GitHub, a chart by star-history.com

Other skills on beautiful-rust.

rust-port

rust-port

Port code from C, C++, Python, Go, JavaScript, or TypeScript into idiomatic Rust that keeps the original behavior: ownership…

rust-review

rust-review

Review existing Rust code for idiom, API design, error handling, safety, and maintainability, and produce a prioritized report…

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills2w309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc2w293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react9d252k
@facebook@facebookInstall Skill

Questions about rust-best-practices.

Which coding agents can use rust-best-practices?
rust-best-practices installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.