repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/rust/SKILL.md

Raw

name: rust description: Rust best practices and pitfalls — ownership patterns, trait objects vs generics, error handling with thiserror/anyhow, build time optimization (sccache, cranelift, feature flags), common anti-patterns. license: MIT

Rust Best Practices

Ownership & Borrowing

Ownership Traps

Borrowing Traps

Lifetimes


Strings & Types

String Traps


Error Handling


Iterators


Concurrency & Memory

Concurrency Traps

Memory Traps


Common Compiler Errors

Error Cause Fix
value moved here Used after move Clone or borrow
cannot borrow as mutable Already borrowed Restructure or RefCell
missing lifetime specifier Ambiguous reference Add <'a>
the trait bound X is not satisfied Missing impl Check trait bounds
cannot move out of borrowed content Deref moves Clone or pattern match

Cargo Tips


Workspace Architecture

One Product = One Repo = One Workspace

Use a Rust workspace when you have:

Canonical workspace structure:

repo/
  Cargo.toml            # workspace root
  crates/
    core/               # pure domain logic (no IO)
    storage/            # DB, filesystem, etc.
    api/                # HTTP/GRPC handlers, DTOs
    cli/                # binary
  tools/                # optional: internal binaries
  tests/                # optional: black-box integration tests

Keep Crates "Thin" and Boundaries "Hard"

Layered architecture:

Critical rule: If core imports tokio, reqwest, or sqlx, you've already lost the separation.

Default to a Small Number of Crates

Start with 2–5 max. Split only when compile times are painful or boundaries are real.

Workspace Dependencies: Centralize Versions

In root Cargo.toml:

[workspace]
members = ["crates/*"]
resolver = "2"

[workspace.dependencies]
anyhow = "*"
thiserror = "*"
serde = { version = "*", features = ["derive"] }
tokio = { version = "*", features = ["macros", "rt-multi-thread"] }

In crate Cargo.toml:

[dependencies]
serde = { workspace = true }

Be Ruthless with Features

[dependencies]
sqlx = { workspace = true, optional = true }

[features]
db = ["dep:sqlx"]

Enforce MSRV + Toolchain


Code Organization

Modules Should Match How You Reason

Organize by capability / domain, not by "models/handlers/utils".

Good organization:

core/src/
  lib.rs
  payment/
    mod.rs
    validation.rs
    pricing.rs
  user/
    mod.rs
    id.rs
    rules.rs

Public API: Small Surface Area

mod payment;
pub use payment::{Payment, PaymentError};

Error Strategy: Pick One and Stick To It

Keep Async at the Edge

If you can keep core synchronous and pure, you gain simpler tests and portability.


Dependency Hygiene

Be Picky: Fewer Deps, Higher-Quality Deps

Every dependency adds build time, audit surface, and semver risk.

Use cargo-deny + cargo-audit

Make dependency issues visible early (licenses, advisories, duplicates).

Don't Use unwrap() in Libraries

In binaries/tests it's fine. In libraries, return errors with context.


Testing Strategy

Think "pyramid":

1. Unit Tests: Fast, Deterministic, Lots

2. Integration Tests: Black-Box the Public API

Use crates/<crate>/tests/*.rs.

3. End-to-End Tests: Few, But Real

Spin up dependencies (db) in containers.

4. Property Tests + Fuzzing

5. Doctests

Keep your public API honest.


Logging and Tracing

Never Use println! - Use Tracing

use tracing::{debug, info, warn, error};

info!("Processing request for user {user_id}");
debug!("Cache hit: {key}");
warn!("Retry attempt {attempt}");
error!("Failed: {err}");

// Bad
println!("...");
dbg!(value);

Use test-log for Tests

use test_log::test;

#[test]
fn test_something() {
    info!("Visible with --nocapture");
}
[dev-dependencies]
test-log = { version = "*", features = ["trace"] }
tracing-subscriber = { version = "*", features = ["env-filter"] }

Run: RUST_LOG=debug cargo test -- --nocapture


Clippy Rules

Inline Format Arguments

// Good
let name = "world";
info!("Hello, {name}!");

// Bad
info!("Hello, {}!", name);

CI / Quality Gates

cargo fmt --check
cargo clippy --all-targets --all-features -D warnings
cargo test --workspace --all-features

Additional: MSRV check, cargo deny, cargo audit


Project Patterns


Rust Build Optimization

Why Build Times Matter

Build time acts as a multiplier for all project work:

Target: 200k lines → ~10 min on GitHub Actions.

CI as Benchmark

Use CI time as primary metric:

CI Caching

Cache dependencies, not project crates:

- uses: Swatinem/rust-cache@v2

CI Optimizations

  1. Split build and test: cargo test --no-run then cargo test
  2. Disable incremental in CI: Closer to from-scratch
  3. Disable debug info: Makes target bigger, hurts caching
  4. Add -D warnings to RUSTFLAGS: Deny warnings for all crates

Profiling: cargo timings

cargo +nightly build -p crate -Z timings --release

Crate Graph

Crates form a DAG - shape affects parallelization:

Slow (sequential):     Fast (parallel):
A -> B -> C -> D         +-  B  -+
                         /         \
                         A  ->  C  ->  E
                         \         /
                          +-  D  -+

Architect for wide graph:

Procedural Macros

Macros block pipelining - rustc must run them to compute metadata.

Thin generic interfaces:

// Ergonomic but compiled per-crate - keep small!
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
    fn inner(path: &Path) -> io::Result<Vec<u8>> { ... }
    inner(path.as_ref())
}

Monitoring: cargo llvm-lines

cargo llvm-lines --lib --release -p crate

References

Markdown source
File outline
---
name: rust
description: Rust best practices and pitfalls — ownership patterns, trait objects vs generics, error handling with thiserror/anyhow, build time optimization (sccache, cranelift, feature flags), common anti-patterns.
license: MIT
---

# Rust Best Practices

## Ownership & Borrowing

### Ownership Traps

- **Variable moved after use** — clone explicitly or borrow with `&`
- **`for item in vec` moves vec** — use `&vec` or `.iter()` to borrow
- **`String` moved into function** — pass `&str` for read-only access

### Borrowing Traps

- **Can't have `&mut` and `&` simultaneously** — restructure or use interior
  mutability
- **Returning reference to local fails** — return owned value instead
- **Mutable borrow through `&mut self` blocks all access** — split struct or use
  `RefCell`

### Lifetimes

- **`'static` means CAN live forever, not DOES** — `String` is 'static capable
- **Struct with reference needs `<'a>`** — `struct Foo<'a> { bar: &'a str }`
- **Function returning ref must tie to input** —
  `fn get<'a>(s: &'a str) -> &'a str`

---

## Strings & Types

### String Traps

- **`s[0]` doesn't compile** — use `.chars().nth(0)` or `.bytes()`
- **`.len()` returns bytes, not chars** — use `.chars().count()`
- **`s1 + &s2` moves s1** — use `format!("{}{}", s1, s2)`

---

## Error Handling

- **`unwrap()` panics** — use `?` or `match` in production
- **`?` needs `Result`/`Option` return type** — main needs `-> Result<()>`
- **`expect("context")` > `unwrap()`** — shows why it panicked

---

## Iterators

- **`.iter()` borrows, `.into_iter()` moves** — choose carefully
- **`.collect()` needs type** — `collect::<Vec<_>>()` or typed binding
- **Iterators are lazy** — nothing runs until consumed

---

## Concurrency & Memory

### Concurrency Traps

- **`Rc` is NOT `Send`** — use `Arc` for threads
- **`Mutex` lock returns guard** — auto-unlocks on drop, don't hold across await
- **`RwLock` deadlock** — reader upgrading to writer blocks forever

### Memory Traps

- **`RefCell` panics at runtime** — if borrow rules violated
- **`Box` for recursive types** — compiler needs known size

---

## Common Compiler Errors

| Error                                 | Cause               | Fix                    |
| ------------------------------------- | ------------------- | ---------------------- |
| `value moved here`                    | Used after move     | Clone or borrow        |
| `cannot borrow as mutable`            | Already borrowed    | Restructure or RefCell |
| `missing lifetime specifier`          | Ambiguous reference | Add `<'a>`             |
| `the trait bound X is not satisfied`  | Missing impl        | Check trait bounds     |
| `cannot move out of borrowed content` | Deref moves         | Clone or pattern match |

---

## Cargo Tips

- **`cargo update` updates Cargo.lock, not Cargo.toml** — manual version bump
  needed
- **Features are additive** — can't disable a feature a dependency enables
- **`[dev-dependencies]` not in release binary** — but in tests/examples
- **`cargo build --release` much faster** — debug builds are slow intentionally

---

## Workspace Architecture

### One Product = One Repo = One Workspace

Use a Rust workspace when you have:

- Multiple crates that ship together (binary + libraries)
- Shared tooling / CI
- Shared versioning policy

**Canonical workspace structure:**

```text
repo/
  Cargo.toml            # workspace root
  crates/
    core/               # pure domain logic (no IO)
    storage/            # DB, filesystem, etc.
    api/                # HTTP/GRPC handlers, DTOs
    cli/                # binary
  tools/                # optional: internal binaries
  tests/                # optional: black-box integration tests
```

### Keep Crates "Thin" and Boundaries "Hard"

**Layered architecture:**

- **core**: Pure logic, types, validation, algorithms. Minimal deps.
- **adapters**: IO boundaries (db, network, rpc, filesystem). Trait-based
  boundary.
- **app / service**: Wiring (DI), config, runtime, orchestration.
- **bins**: CLI/daemon that just calls "app".

**Critical rule:** If `core` imports `tokio`, `reqwest`, or `sqlx`, you've
already lost the separation.

### Default to a Small Number of Crates

Start with 2–5 max. Split only when compile times are painful or boundaries are
real.

### Workspace Dependencies: Centralize Versions

In root `Cargo.toml`:

```toml
[workspace]
members = ["crates/*"]
resolver = "2"

[workspace.dependencies]
anyhow = "*"
thiserror = "*"
serde = { version = "*", features = ["derive"] }
tokio = { version = "*", features = ["macros", "rt-multi-thread"] }
```

In crate `Cargo.toml`:

```toml
[dependencies]
serde = { workspace = true }
```

### Be Ruthless with Features

- Prefer additive features vs "feature flags that change semantics"
- Put "heavy" deps behind features (db, http, metrics)

```toml
[dependencies]
sqlx = { workspace = true, optional = true }

[features]
db = ["dep:sqlx"]
```

### Enforce MSRV + Toolchain

- Pin toolchain with `rust-toolchain.toml`
- Decide MSRV and test it in CI

---

## Code Organization

### Modules Should Match How You Reason

Organize by capability / domain, not by "models/handlers/utils".

**Good organization:**

```text
core/src/
  lib.rs
  payment/
    mod.rs
    validation.rs
    pricing.rs
  user/
    mod.rs
    id.rs
    rules.rs
```

### Public API: Small Surface Area

- Make most things `pub(crate)` by default
- Re-export a curated API from `lib.rs`

```rust
mod payment;
pub use payment::{Payment, PaymentError};
```

### Error Strategy: Pick One and Stick To It

- Library crates: `thiserror` for typed errors
- Binaries: `anyhow` at the top level

### Keep Async at the Edge

If you can keep core synchronous and pure, you gain simpler tests and
portability.

---

## Dependency Hygiene

### Be Picky: Fewer Deps, Higher-Quality Deps

Every dependency adds build time, audit surface, and semver risk.

### Use `cargo-deny` + `cargo-audit`

Make dependency issues visible early (licenses, advisories, duplicates).

### Don't Use `unwrap()` in Libraries

In binaries/tests it's fine. In libraries, return errors with context.

---

## Testing Strategy

Think "pyramid":

### 1. Unit Tests: Fast, Deterministic, Lots

- Put tests close to code: `mod tests {}` in the same file
- Test invariants and edge cases
- Avoid filesystem/network in unit tests

### 2. Integration Tests: Black-Box the Public API

Use `crates/<crate>/tests/*.rs`.

### 3. End-to-End Tests: Few, But Real

Spin up dependencies (db) in containers.

### 4. Property Tests + Fuzzing

- `proptest` for invariants
- `cargo-fuzz` for parsers

### 5. Doctests

Keep your public API honest.

---

## Logging and Tracing

### Never Use `println!` - Use Tracing

```rust
use tracing::{debug, info, warn, error};

info!("Processing request for user {user_id}");
debug!("Cache hit: {key}");
warn!("Retry attempt {attempt}");
error!("Failed: {err}");

// Bad
println!("...");
dbg!(value);
```

### Use `test-log` for Tests

```rust
use test_log::test;

#[test]
fn test_something() {
    info!("Visible with --nocapture");
}
```

```toml
[dev-dependencies]
test-log = { version = "*", features = ["trace"] }
tracing-subscriber = { version = "*", features = ["env-filter"] }
```

Run: `RUST_LOG=debug cargo test -- --nocapture`

---

## Clippy Rules

### Inline Format Arguments

```rust
// Good
let name = "world";
info!("Hello, {name}!");

// Bad
info!("Hello, {}!", name);
```

---

## CI / Quality Gates

```bash
cargo fmt --check
cargo clippy --all-targets --all-features -D warnings
cargo test --workspace --all-features
```

Additional: MSRV check, `cargo deny`, `cargo audit`

---

## Project Patterns

- **CLI**: Thin binary → lib (for testability)
- **Services**: Separate protocol definitions; feature-flag transport
- **ZK/crypto**: Isolate no_std core; separate proving/verification crates
- **WASM**: Separate bindings; platform-agnostic core

---

# Rust Build Optimization

## Why Build Times Matter

Build time acts as a **multiplier** for all project work:

- Breaks flow state, causes context switches
- Small increases go unnoticed until major problem
- Once slow, improving takes long

**Target**: 200k lines → ~10 min on GitHub Actions.

## CI as Benchmark

Use CI time as primary metric:

- Standardization: CI runs consistently
- Use merge robot for always-green main

## CI Caching

**Cache dependencies, not project crates:**

```yaml
- uses: Swatinem/rust-cache@v2
```

## CI Optimizations

1. **Split build and test**: `cargo test --no-run` then `cargo test`
2. **Disable incremental in CI**: Closer to from-scratch
3. **Disable debug info**: Makes target bigger, hurts caching
4. **Add `-D warnings` to RUSTFLAGS**: Deny warnings for all crates

## Profiling: cargo timings

```bash
cargo +nightly build -p crate -Z timings --release
```

## Crate Graph

**Crates form a DAG - shape affects parallelization:**

```
Slow (sequential):     Fast (parallel):
A -> B -> C -> D         +-  B  -+
                         /         \
                         A  ->  C  ->  E
                         \         /
                          +-  D  -+
```

Architect for wide graph:

- Common vocabulary crate
- Independent feature crates
- Leaf crate to tie together

## Procedural Macros

Macros block pipelining - rustc must run them to compute metadata.

**Thin generic interfaces:**

```rust
// Ergonomic but compiled per-crate - keep small!
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
    fn inner(path: &Path) -> io::Result<Vec<u8>> { ... }
    inner(path.as_ref())
}
```

## Monitoring: cargo llvm-lines

```bash
cargo llvm-lines --lib --release -p crate
```

---

## References

- https://doc.rust-lang.org/book/
- https://rust-lang.github.io/rustc-dev-guide/