Token导航 LogoToken导航TokenDH.com
开发规范执行命令github未标认证来源可访问许可证需确认审计通过

rust-best-practicesRust 最佳实践

Agent Skill

rust-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,223

周安装

52

GitHub Stars

323

下载量

428
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-best-practices(Rust 最佳实践)
来源仓库:https://github.com/pedronauck/skills
仓库路径:skills/rust-best-practices
安装命令:
npx skills add https://github.com/pedronauck/skills --skill rust-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/pedronauck/skills --skill rust-best-practices

简介

rust-best-practices 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用。
  • 安装前需确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 建议结合来源仓库和原始 README 核验具体用法和功能边界。

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

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.31%
按下载量换算164

Claude

29.77%
按下载量换算127

Cursor

19.99%
按下载量换算86

Gemini CLI

8.41%
按下载量换算36

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/pedronauck/skills --skill rust-best-practices 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills