rust-best-practices
Comprehensive Rust coding guidelines covering ownership, error handling, async patterns, traits, testing, performance, clippy, and documentation. Use when writing new Rust code, reviewing or refactoring existing Rust, implementing async systems with Tokio, designing error hierarchies, choosing between borrowing and cloning, setting up tests or benchmarks, configuring linting, or optimizing performance. Do not use for non-Rust languages or general software architecture unrelated to Rust idioms.
What this skill does
# 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:
| Topic | Reference | Load When |
|-------|-----------|-----------|
| Coding Style | `references/coding-style.md` | Naming, imports, iterators, comments, string handling, macros |
| Error Handling | `references/error-handling.md` | Result, Option, ?, thiserror, anyhow, custom errors, async errors |
| Ownership & Pointers | `references/ownership-and-pointers.md` | Lifetimes, borrowing, smart pointers, Pin, Cow, interior mutability |
| Traits & Generics | `references/traits-and-generics.md` | Trait design, dispatch, GATs, sealed traits, type state pattern |
| Async & Concurrency | `references/async-and-concurrency.md` | Tokio, channels, streams, shutdown, runtime config, async traits |
| Sync Concurrency | `references/concurrency-sync.md` | Atomics, Mutex, RwLock, lock ordering, Send/Sync, memory ordering |
| Testing | `references/testing.md` | Unit/integration/doc tests, snapshot, proptest, mockall, benchmarks, fuzz |
| Performance | `references/performance.md` | Profiling, flamegraph, cloning, stack vs heap, iterators, allocation |
| Clippy & Linting | `references/clippy-and-linting.md` | Clippy config, key lints, workspace setup, #[expect] vs #[allow] |
| Documentation | `references/documentation.md` | Doc 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()?`
| Pointer | When 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:
```rust
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
| Channel | Use Case |
|---------|----------|
| `mpsc` | Multi-producer, single-consumer message passing |
| `broadcast` | Multi-producer, multi-consumer event fan-out |
| `oneshot` | Single value, single use (request-response) |
| `watch` | Latest-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
```
| Lint | Catches |
|------|---------|
| `redundant_clone` | Unnecessary `.clone()` calls |
| `needless_borrow` | Unnecessary `&` borrows |
| `large_enum_variant` | Oversized variants (consider `Box`) |
| `needless_collect` | Premature `.collect()` before iteration |
| `map_unwrap_or` | `.map().unwrap_or()` chains |
| `unnecessary_wraps` | Functions always returning `Ok`/`Some` |
| `clone_on_copy` | `.clone()` on `Copy` types |
- Use `#[expect(clippy::lint)]` over `#[allow(...)]` — `expect` warns Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.