Xpersona
R

Rust Best Practices

CLAWHUB · Unverified

Development guidance for writing idiomatic Rust. Use when: (1) writing new Rust functions or modules, (2) choosing between borrowing, cloning, or ownership p... Skill: Rust Best Practices Owner: anderskev Summary: Development guidance for writing idiomatic Rust. Use when: (1) writing new Rust functions or modules, (2) choosing between borrowing, cloning, or ownership p... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-05-23T05:43:53.014Z | auto - Added coverage of advanced patterns (“Wild Patterns”): drop guards, extension traits, index pointers, and crate preludes. - Upd

62
Rank
84
Safety
1.3k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17b1fzefm8nj8j1sdkzrze7gn83pfrg:rust-best-practices
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-anderskev-rust-best-practices/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

144,871 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: rust-best-practices
description: >
  Development guidance for writing idiomatic Rust. Use when:
  (1) writing new Rust functions or modules,
  (2) choosing between borrowing, cloning, or ownership patterns,
  (3) implementing error handling with Result types,
  (4) optimizing Rust code for performance,
  (5) configuring clippy and linting for a project,
  (6) deciding between static and dynamic dispatch,
  (7) writing documentation or doc tests.
---

# Rust Best Practices

Guidance for writing idiomatic, performant, and safe Rust code. This is a development skill, not a review skill -- use it when building, not reviewing.

## Quick Reference

| Topic | Key Rule | Reference |
|-------|----------|-----------|
| Ownership | Borrow by default, clone only when you need a separate owned copy | [references/coding-idioms.md](references/coding-idioms.md) |
| Clippy | Run `cargo clippy -- -D warnings` on every commit; configure workspace lints | [references/clippy-config.md](references/clippy-config.md) |
| Performance | Don't guess, measure. Profile with `--release` first. Watch monomorphization + cache-line alignment at scale | [references/performance.md](references/performance.md) |
| Generics | Static dispatch by default, dynamic dispatch when you need mixed types | [references/generics-dispatch.md](references/generics-dispatch.md) |
| Type State | Encode state in the type system when invalid operations should be compile errors | [references/type-state-pattern.md](references/type-state-pattern.md) |
| Documentation | `//` for why, `///` for what and how, `//!` for module/crate purpose | [references/documentation.md](references/documentation.md) |
| Pointers | Choose pointer types based on ownership needs and threading model | [references/pointer-types.md](references/pointer-types.md) |
| API Design | Unsurprising, flexible, obvious, constrained — encode invariants in types; watch hidden contracts (re-exports, auto-traits) | [references/api-design.md](references/api-design.md) |
| Wild Patterns | Drop guards, extension traits, index pointers, crate preludes — battle-tested idioms from mature crates | [references/coding-idioms.md](references/coding-idioms.md) |
| Ecosystem | Evaluate crates, pick error handling strategy, stay current | [references/ecosystem-patterns.md](references/ecosystem-patterns.md) |

## Gates

Short **sequences with pass conditions** before claiming outcomes that need evidence (not an internal “I checked”).

### Clippy clean

1. From the workspace root (or with `-p <crate>`), run: `cargo clippy --all-targets --all-features -- -D warnings`.
2. **Pass:** exit status is `0` and the invocation finishes without Clippy-deny failures.

### Performance claim

1. Build with `cargo build --release` (or your benchmark harness) under the same profile you ship or measure.
2. Capture a **before** and **after** number from the same tool and metric (name both), e.g. Criterion `ns/iter`, `heaptrack` allocations, or a flamegraph path on di

_meta.json

{
  "ownerId": "kn79190nfmdb20hk6xjhzt2zv583844x",
  "slug": "rust-best-practices",
  "version": "1.0.3",
  "publishedAt": 1779515033014
}

references/api-design.md

# API Design

## Four Principles

Every Rust interface should be **unsurprising** (follow naming conventions and standard trait expectations), **flexible** (avoid unnecessary restrictions on callers), **obvious** (use types and docs to prevent misuse), and **constrained** (expose only what you intend to support long-term).

## Naming Conventions

Follow the Rust API Guidelines. Reuse well-known names so users can rely on intuition:

- `iter` takes `&self` and returns an iterator
- `into_inner` takes `self` and returns a wrapped value
- `SomethingError` implements `std::error::Error`

Avoid using familiar names for unfamiliar behavior -- if `iter` takes `self`, users will write bugs.

## Standard Trait Implementations

Eagerly implement standard traits even if you don't need them yet. Users cannot implement foreign traits on your types due to coherence rules.

**Priority order:**
1. `Debug` -- nearly every type should have it
2. `Send`, `Sync` -- document if intentionally missing
3. `Clone`, `Default` -- expected for most types
4. `PartialEq`, `Hash` -- needed for collections and assertions
5. `Serialize`/`Deserialize` -- behind a `serde` feature flag

Avoid deriving `Copy` by default. It changes move semantics, and removing it later is a breaking change.

## Making Invalid States Unrepresentable

Use the type system to prevent misuse at compile time rather than panicking at runtime.

```rust
// BAD -- runtime check, caller can pass wrong combination
fn launch(rocket: &mut Rocket, is_fueled: bool, is_on_ground: bool) {
    assert!(is_fueled && is_on_ground);
}

// GOOD -- invalid calls are compile errors
struct Grounded;
struct Launched;
struct Rocket<Stage = Grounded> {
    stage: std::marker::PhantomData<Stage>,
}

impl Rocket<Grounded> {
    fn launch(self) -> Rocket<Launched> { /* ... */ }
}
```

Combine related booleans into enums. If a pointer is only valid when a flag is true, use an `Option` or a single enum with the data inside the relevant variant.

## Builder Pattern

Use when constructing types with many optional fields or when required fields must be validated before use.

```rust
pub struct ServerConfig { /* private fields */ }

pub struct ServerConfigBuilder {
    host: String,
    port: Option<u16>,
    tls: Option<TlsConfig>,
}

impl ServerConfigBuilder {
    pub fn new(host: impl Into<String>) -> Self {
        Self { host: host.into(), port: None, tls: None }
    }

    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    pub fn build(self) -> Result<ServerConfig, ConfigError> {
        // validate and construct
    }
}
```

For builders with required stages, combine with type-state pattern (see [type-state-pattern.md](type-state-pattern.md)).

## `impl Trait` in Argument vs Return Position

**Argument position** (`fn foo(x: impl Read)`) -- syntactic sugar for generics. Caller chooses the concrete type. Monomorphized, so each type gets its own copy.

**Return position** (`fn foo() ->

references/clippy-config.md

# Clippy Configuration

## Daily Workflow Command

Run on every commit or PR:

```shell
cargo clippy --all-targets --all-features --locked -- -D warnings
```

- `--all-targets`: checks library, tests, benches, examples
- `--all-features`: enables all feature flags to catch conditional code
- `--locked`: requires Cargo.lock to be up-to-date (omit for library crates that don't commit `Cargo.lock`)
- `-D warnings`: treats warnings as errors

Add to your Makefile, Justfile, xtask, or CI pipeline.

## Workspace Lint Configuration

Configure in `Cargo.toml` for consistent enforcement:

```toml
[workspace.lints.rust]
future-incompatible = "warn"
nonstandard_style = "deny"

[workspace.lints.clippy]
all = { level = "deny", priority = 10 }
redundant_clone = { level = "deny", priority = 9 }
manual_while_let_some = { level = "deny", priority = 4 }
pedantic = { level = "warn", priority = 3 }
```

Individual crates inherit workspace lints:

```toml
[lints]
workspace = true
```

Higher priority numbers win when lints conflict.

## Key Lints to Enforce

| Lint | Why | Category |
|------|-----|----------|
| `redundant_clone` | Detects unnecessary clones with performance impact | perf |
| `large_enum_variant` | Warns about oversized variants -- consider Boxing | perf |
| `needless_collect` | Prevents unnecessary intermediate collection allocation | nursery |
| `needless_borrow` | Removes redundant `&` borrowing | style |
| `clone_on_copy` | Catches `.clone()` on Copy types like `u32` | complexity |
| `unnecessary_wraps` | Function always returns Some/Ok -- drop the wrapper | pedantic |
| `manual_ok_or` | Suggests `.ok_or_else()` over match | style |

Run the perf lint group specifically:

```shell
cargo clippy -- -D clippy::perf
```

## Lint Suppression

### Use `#[expect]` as the Default

`#[expect]` (stable since Rust 1.81) is the standard for lint suppression. It warns when the lint no longer triggers, preventing stale suppressions from accumulating. Always use `#[expect]` instead of `#[allow]`:

```rust
// BAD - stale allow stays forever unnoticed
#[allow(clippy::large_enum_variant)]
enum Message { /* ... */ }

// GOOD - compiler warns when lint is no longer needed
#[expect(clippy::large_enum_variant)]
enum Message { /* ... */ }
```

When migrating an existing codebase, replace all `#[allow(lint)]` with `#[expect(lint)]`. The compiler will immediately flag any suppressions that are no longer needed, letting you clean up dead lint suppression.

For crate-level suppression where `#![expect(...)]` is not practical (e.g., generated code), `#![allow(...)]` remains acceptable with a comment explaining why.

### Always Add Justification

```rust
// Intentionally large for cache-line alignment
#[expect(clippy::large_enum_variant, reason = "cache-line alignment")]
enum Packet {
    Header(u8),
    Payload([u8; 1024]),
}
```

The `reason` parameter (stable since 1.81) documents intent inline and shows up in compiler output when the expect becomes unfulfilled.

### Handl

references/coding-idioms.md

# Coding Idioms

## Borrowing Over Cloning

Default to borrowing (`&T`). Clone only when you genuinely need a separate owned copy.

### When Clone is Appropriate

- Shared ownership via `Arc::clone(&arc)` (cheap atomic increment)
- Immutable snapshots where the original must be preserved
- When the API requires owned data and the caller still needs the original
- Caching results returned multiple times

### Clone Traps to Avoid

```rust
// BAD - cloning to avoid lifetime annotations
fn process(thing: &Thing) {
    let owned = thing.clone(); // if you need ownership, take it in the signature
    consume(owned);
}

// GOOD - take ownership explicitly
fn process(thing: Thing) {
    consume(thing);
}
```

```rust
// BAD - cloning inside iterator
items.iter().map(|x| x.clone()).collect::<Vec<_>>();

// GOOD - use .cloned() or .copied()
items.iter().cloned().collect::<Vec<_>>();
items.iter().copied().collect::<Vec<_>>(); // for Copy types
```

### Prefer Borrowed Parameters

```rust
// DO - borrow when you only read
fn greet(name: &str) {
    println!("Hello, {name}");
}

// DO - use slices over owned collections
fn sum(values: &[i32]) -> i32 {
    values.iter().sum()
}

// DON'T - force callers to allocate
fn greet(name: String) {
    println!("Hello, {name}");
}
```

For maximum flexibility in public APIs, use `impl AsRef<str>` or `impl Into<String>`.

## Copy Trait

### When to Derive Copy

- All fields are `Copy` themselves
- Struct is small (<=24 bytes / 2-3 machine words)
- Type is plain data without heap allocations

```rust
// GOOD - small plain data
#[derive(Debug, Copy, Clone)]
struct Point { x: f32, y: f32, z: f32 }

// GOOD - tag-like enum
#[derive(Debug, Copy, Clone)]
enum Direction { North, South, East, West }

// CAN'T - String is not Copy
struct User { age: i32, name: String }
```

Enum size equals the largest variant. Keep variants small or Box large payloads.

## Option and Result Handling

### Pattern Selection

| Pattern | Use When |
|---------|----------|
| `let Ok(x) = expr else { return ... }` | Early return, divergent code doesn't need error value |
| `match` | Pattern matching inner variants, transforming Result/Option shapes |
| `if let ... else` | Else branch needs computation with the value |
| `?` operator | Propagating errors to the caller |

```rust
// Early return with let-else
let Some(config) = load_config() else {
    return Err(AppError::MissingConfig);
};

// Pattern matching inner variants
match result {
    Ok(Direction::North) => handle_north(),
    Ok(other) => handle_other(other),
    Err(e) => handle_error(e),
}

// Propagation with ?
fn process(req: &Request) -> Result<Response, Error> {
    let body = validate(req)?;
    let user = authorize(&body)?;
    Ok(handle(user)?)
}
```

### Avoid These

```rust
// BAD - unwrap in production
let port = config.port.unwrap();

// BAD - match that should be .ok() or .ok_or()
match result {
    Ok(v) => Some(v),
    Err(_) => None,
}
// GOOD
result.ok()
```

## Prevent E

Sponsored

Ads related to Rust Best Practices and adjacent AI workflows.