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★ 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 andDrop, polymorphism with traits and enums, and nullability withOption. Inheritance-flavored tricks (Derefto a "base" struct,Manager/Factorytypes,throw_if_nullhelpers) 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,
Stringor&strrather thanimpl Into<String>parameters,anyhow-style errors,Vecreturn 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.expectwarns 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, withcargo clippy -- -D warnings. - Configure lints once in
Cargo.toml([lints]or[workspace.lints]), not with scattered crate attributes. If a project has none, suggestlints/lints.tomlandlints/clippy.tomlfrom https://github.com/morganlinton/BeautifulRust; the suppression lints in it needrust-version1.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:
- Extend a temporary with a named
let, or shorten a borrow with a block. - Split a long expression into typed intermediates so the failing step is visible.
- Move a field out of
&mut selfwithstd::mem::take(needsDefault),std::mem::replace, orOption::takeinstead of cloning it. - 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.
- Clone small, immutable data deliberately, and say so in a comment if it's not obvious.
- Use indices into an owning
Vec, orRc<RefCell<_>>withWeakback-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
Установить rust-best-practices в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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 запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic