Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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…

morganlintonот morganlinton★ 2 188 звёзд на GitHub

Об этом скилле

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

Полный SKILL.md на GitHub

Установить rust-best-practices в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

evals/bevy-arena-regen/case.yamlevals/bevy-arena-regen/files/Cargo.lockevals/bevy-arena-regen/files/Cargo.tomlevals/bevy-arena-regen/files/src/lib.rsevals/bevy-arena-regen/graders/01-builds-and-tests-pass.mdevals/bevy-arena-regen/graders/02-regen-tested-headless.mdevals/bevy-arena-regen/graders/03-system-params-by-value.mdevals/bevy-arena-regen/graders/04-keeps-bevy-prelude.mdevals/bevy-arena-regen/graders/05-plain-data-components.mdevals/bevy-arena-regen/graders/06-ordered-after-damage.mdevals/bevy-arena-regen/graders/07-no-panicking-queries.mdevals/bevy-arena-regen/graders/08-clippy-clean.mdevals/bevy-arena-regen/graders/09-health-never-exceeds-max.mdevals/bevy-arena-regen/graders/10-existing-code-not-rewritten.mdevals/bevy-arena-regen/place-files.shevals/bevy-arena-regen/prompt.mdevals/log-summary-cli/case.yamlevals/log-summary-cli/graders/01-never-panics-on-bad-input.mdevals/log-summary-cli/graders/02-errors-name-the-file.mdevals/log-summary-cli/graders/03-malformed-lines-counted.mdevals/log-summary-cli/graders/04-paths-as-path-types.mdevals/log-summary-cli/graders/05-sorted-and-skipped-count.mdevals/log-summary-cli/graders/06-dependency-ranges.mdevals/log-summary-cli/graders/07-map-based-counting.mdevals/log-summary-cli/graders/08-aggregation-unit-tested.mdevals/log-summary-cli/prompt.mdevals/refactor-inventory-module/case.yamlevals/refactor-inventory-module/files/inventory.rsevals/refactor-inventory-module/graders/01-deny-warnings-removed.mdevals/refactor-inventory-module/graders/02-no-rc-refcell-in-api.mdevals/refactor-inventory-module/graders/03-borrowed-param-types.mdevals/refactor-inventory-module/graders/04-error-implements-error.mdevals/refactor-inventory-module/graders/05-no-unwrap-on-fallible-paths.mdevals/refactor-inventory-module/graders/06-getter-renamed.mdevals/refactor-inventory-module/graders/07-bool-param-replaced.mdevals/refactor-inventory-module/graders/08-deterministic-report.mdevals/refactor-inventory-module/graders/09-format-over-concat.mdevals/refactor-inventory-module/graders/10-no-check-then-unwrap.mdevals/refactor-inventory-module/graders/11-changes-listed-with-reasons.mdevals/refactor-inventory-module/graders/12-signature-changes-called-out.md

FAQ

Что делает скилл 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 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?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rust-best-practices запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить rust-best-practices с