rust-best-practices

pedronauck/skills

Правила кода на Rust: владение, ошибки, async, трейты, тесты, производительность, clippy.

Звёзды655
Форки95
Авторpedronauck
Обновлённоя 16 2026

Установка

SKILL.md

Rust Best Practices

Unified Rust guidelines covering coding style, ownership, error handling, async patterns, traits, testing, performance, linting, and documentation. Apply when writing or reviewing Rust code.

When to Apply

  • Writing new Rust code or designing APIs
  • Reviewing or refactoring existing Rust code
  • Implementing async systems with Tokio
  • Designing error hierarchies with thiserror/anyhow
  • Choosing between borrowing, cloning, or ownership transfer
  • Setting up tests, benchmarks, or snapshot testing
  • Configuring clippy lints and workspace settings
  • Optimizing Rust code for performance

Reference Guide

Load detailed guidance based on context. Read the relevant file when the topic arises:

TopicReferenceLoad When
Coding Stylereferences/coding-style.mdNaming, imports, iterators, comments, string handling, macros
Error Handlingreferences/error-handling.mdResult, Option, ?, thiserror, anyhow, custom errors, async errors
Ownership & Pointersreferences/ownership-and-pointers.mdLifetimes, borrowing, smart pointers, Pin, Cow, interior mutability
Traits & Genericsreferences/traits-and-generics.mdTrait design, dispatch, GATs, sealed traits, type state pattern
Async & Concurrencyreferences/async-and-concurrency.mdTokio, channels, streams, shutdown, runtime config, async traits
Sync Concurrencyreferences/concurrency-sync.mdAtomics, Mutex, RwLock, lock ordering, Send/Sync, memory ordering
Testingreferences/testing.mdUnit/integration/doc tests, snapshot, proptest, mockall, benchmarks, fuzz
Performancereferences/performance.mdProfiling, flamegraph, cloning, stack vs heap, iterators, allocation
Clippy & Lintingreferences/clippy-and-linting.mdClippy config, key lints, workspace setup, #[expect] vs #[allow]
Documentationreferences/documentation.mdDoc comments, rustdoc, doc lints, coverage checklist

Quick Reference: Coding Style

  • Prefer &T over .clone() unless ownership transfer is required
  • Use &str over String, &[T] over Vec<T> in function parameters
  • No get_ prefix on getters: fn name() not fn get_name()
  • Conversion naming: as_ (cheap borrow), to_ (expensive/cloning), into_ (ownership transfer)
  • Iterator methods: iter() / iter_mut() / into_iter()
  • Import ordering: std -> external crates -> workspace crates -> super:: -> crate::
  • Comments explain why (safety, workarounds), not what
  • Use format! over string concatenation with +
  • Prefer s.bytes() over s.chars() for ASCII-only operations
  • Avoid macros unless necessary; prefer functions or generics

Quick Reference: Error Handling

  • Return Result<T, E> for fallible operations; reserve panic! for unrecoverable bugs
  • No unwrap() in production. Use expect() with descriptive message only when the value is logically guaranteed. Prefer ?, if let, let...else for all other cases
  • Use thiserror for library/crate errors, anyhow for binaries only
  • Prefer ? operator over match chains for error propagation
  • Use _else variants (ok_or_else, unwrap_or_else) to prevent eager allocation
  • Use inspect_err and map_err for logging and transforming errors
  • assert! at function entry for invariant checking (debug builds)

Quick Reference: Ownership & Pointers

  • Small Copy types (<=24 bytes, all fields Copy, no heap) pass by value
  • Use Cow<'_, T> when data may or may not need ownership
  • Meaningful lifetime names: 'src, 'ctx, 'conn — not just 'a
  • Use try_borrow() on RefCell to avoid panics; prefer over direct .borrow_mut()
  • Shadowing for transformations: let x = x.parse()?
PointerWhen to Use
Box<T>Single ownership, heap allocation, recursive types
Rc<T>Shared ownership, single-threaded
Arc<T>Shared ownership, multi-threaded
Cell<T> / RefCell<T>Interior mutability, single-threaded
Mutex<T> / RwLock<T>Interior mutability, multi-threaded

Quick Reference: Traits & Generics

  • Prefer generics (static dispatch) by default for zero-cost abstractions
  • Use dyn Trait only when heterogeneous collections or plugin architectures are needed
  • Box at API boundaries, not internally
  • Object safety: no generic methods, no Self: Sized, methods use &self/&mut self/self
  • Use sealed traits to prevent external implementors
  • Type state pattern encodes valid states in the type system:
struct Connection<S> { _state: PhantomData<S> }
struct Disconnected;
struct Connected;
impl Connection<Connected> { fn send(&self, data: &[u8]) { /* ... */ } }

Quick Reference: Async & Concurrency

  • Async for I/O-bound work, sync for CPU-bound work
  • Never hold locks across .await points — use scoped guards
  • Never use std::thread::sleep in async — use tokio::time::sleep
  • Never spawn unboundedly — use semaphores for limits
  • Ensure Send bounds on spawned futures
  • Use JoinSet for managing multiple concurrent tasks
  • Use CancellationToken (from tokio_util) for graceful shutdown
  • Instrument with tracing + #[instrument] for async debugging
ChannelUse Case
mpscMulti-producer, single-consumer message passing
broadcastMulti-producer, multi-consumer event fan-out
oneshotSingle value, single use (request-response)
watchLatest-value-only, change notification
  • Sync channels: crossbeam::channel over std::sync::mpsc
  • Async channels: tokio::sync::{mpsc, broadcast, oneshot, watch}
  • Atomics (AtomicBool, AtomicUsize) over Mutex for primitive types
  • Choose memory ordering carefully: Relaxed / Acquire / Release / SeqCst

Quick Reference: Testing

  • Name tests descriptively: process_should_return_error_when_input_empty()
  • One assertion per test when possible; include formatted failure messages
  • Group tests in mod blocks by unit of work
  • Use doc tests (///) for public API examples; run separately with cargo test --doc
  • Snapshot testing: cargo insta test then cargo insta review; redact unstable fields
  • rstest for parameterized tests with #[case::name] labels
  • proptest for property-based testing with custom strategies
  • mockall with #[automock] for mocking traits
  • criterion for benchmarks with iter_batched and BenchmarkId
  • cargo-fuzz with libfuzzer_sys for fuzz testing
  • cargo-tarpaulin or cargo-llvm-cov for code coverage
  • sqlx::test for database integration tests with automatic pool injection
  • Use #[should_panic] and #[ignore] attributes where appropriate

Quick Reference: Performance

  • Golden rule: don't guess, measure. Always benchmark with --release
  • Run cargo clippy -- -D clippy::perf for performance-related hints
  • Use cargo flamegraph or samply (macOS) for profiling
  • Avoid cloning in loops; clone at the last moment only
  • Pre-allocate: Vec::with_capacity(), String::with_capacity()
  • Prefer iterators over manual for loops; avoid intermediate .collect()
  • Stack for small types, heap for large/recursive; use smallvec for large const arrays
  • Use Cow<'_, T> to avoid unnecessary allocation
  • Prefer s.bytes() over s.chars() for ASCII-only string operations

Quick Reference: Clippy & Linting

Run regularly:

cargo clippy --all-targets --all-features --locked -- -D warnings
LintCatches
redundant_cloneUnnecessary .clone() calls
needless_borrowUnnecessary & borrows
large_enum_variantOversized variants (consider Box)
needless_collectPremature .collect() before iteration
map_unwrap_or.map().unwrap_or() chains
unnecessary_wrapsFunctions always returning Ok/Some
clone_on_copy.clone() on Copy types
  • Use #[expect(clippy::lint)] over #[allow(...)] — expect warns when lint no longer applies
  • Add justification comment on every suppression
  • Set #![warn(clippy::all)] as workspace minimum
  • Configure workspace lints in Cargo.toml with priority levels

Quick Reference: Documentation

  • // comments explain why: safety invariants, workarounds, design rationale
  • /// doc comments explain what and how for all public items
  • //! for module-level and crate-level documentation at top of lib.rs/mod.rs
  • Every TODO needs a linked issue: // TODO(#42): description
  • Enable #![deny(missing_docs)] for libraries
  • Include # Examples, # Errors, # Panics, # Safety sections in doc comments
Doc LintPurpose
missing_docsEnsure all public items documented
broken_intra_doc_linksCatch dead cross-references
missing_panics_docDocument panic conditions
missing_errors_docDocument error conditions
missing_safety_docDocument unsafe safety requirements

Quick Reference: Data Types & Patterns

  • Use newtypes for domain semantics: struct Email(String)
  • Prefer slice patterns: if let [first, .., last] = slice
  • Use arrays for fixed sizes; avoid Vec when length is known at compile time
  • Shadowing for transformation: let x = x.parse()?
  • Cow<str> when data might need modification of borrowed data
  • contains() on strings is O(n*m) — avoid nested string iteration

Deprecated to Modern Migration

DeprecatedBetterSince
lazy_static!std::sync::OnceLockRust 1.70
once_cell::Lazystd::sync::LazyLockRust 1.80
std::sync::mpsccrossbeam::channel (sync)—
std::sync::Mutexparking_lot::Mutex (recommended)—
failure / error-chainthiserror / anyhow—
try!()? operatorRust 2018
async-trait crateNative async fn in traits (1.75+, limited)Rust 1.75

Cargo.toml Essentials

Recommended dependencies:

[dependencies]
thiserror = "2"
anyhow = "1"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = "0.3"

[dev-dependencies]
rstest = "0.25"
proptest = "1"
mockall = "0.13"
criterion = { version = "0.5", features = ["html_reports"] }
insta = { version = "1", features = ["yaml"] }

Workspace lints (Cargo.toml):

[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }

rustfmt.toml:

reorder_imports = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"

Constraints

MUST DO

  1. Use ownership and borrowing for memory safety
  2. Handle all errors explicitly via Result/Option — no silent failures
  3. Use thiserror for library errors, anyhow for binaries
  4. Minimize unsafe code; document all unsafe blocks with safety invariants
  5. Use the type system for compile-time guarantees
  6. Run cargo clippy and fix all warnings
  7. Use cargo fmt for consistent formatting
  8. Write tests including doc tests for public APIs
  9. Add /// documentation with examples for all public items
  10. Use tracing for observability in async code
  11. When reviewing or writing code, suggest a testing approach using the recommended tools (rstest, proptest, insta, mockall, criterion) — even if the user did not ask for tests

MUST NOT DO

  1. Use unwrap() in production code
  2. Create memory leaks or dangling pointers
  3. Use unsafe without documented safety invariants
  4. Ignore clippy warnings without #[expect(...)] and justification
  5. Hold locks across .await points
  6. Use std::thread::sleep in async context
  7. Skip error handling or use panic! for recoverable errors
  8. Use String where &str suffices; clone unnecessarily
  9. Spawn tasks unboundedly without semaphore limits
  10. Mix blocking and async code without spawn_blocking

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: rust-best-practices](https://darkplay.ru/ai/skills/pedronauck-skills-rust-best-practices)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★
Rust Build Resolveraffaan-m · Специалист по ошибкам сборки Rust: cargo, borrow checker и Cargo.toml.
225 587 ★
Rust Revieweraffaan-m · Ревьюер Rust: владение, времена жизни, ошибки, unsafe и идиомы.
225 587 ★
plugin-devanthropics · Полный набор инструментов для разработки плагинов Claude Code. Включает 7 экспертных…
34 комп.
ruflo-federationruvnet · Федерация агентов между установками с безопасностью zero-trust, потоком данных с…
240 комп.
ruflo-neural-traderruvnet · Нейросетевые торговые стратегии: самообучающиеся модели LSTM/Transformer/N-BEATS с…
240 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8