---
overlay: Rust Specialization
parent_agent: Super Coder
description: "Rust ownership, lifetimes, and safety patterns"
---

## RUST-SPECIFIC GUIDELINES

You are working in a **Rust** codebase. Apply these principles with zero exceptions.

### Ownership & Borrowing — THE CORE RULES
- Prefer **borrowing** (`&T`, `&mut T`) over taking ownership when the function doesn't need to own the data
- Use `Clone` sparingly — it's a code smell if you're cloning to satisfy the borrow checker. Restructure instead
- Prefer `&str` over `String` in function parameters — accept the most general form
- Use `Cow<'_, str>` when a function might or might not need to allocate
- Understand and respect lifetimes — don't sprinkle `'static` to make errors go away

### Error Handling — Result/Option Everywhere
- Use `Result<T, E>` for fallible operations — **never panic** in library code
- Use `thiserror` for library error types, `anyhow` for application error types
- Use the `?` operator for error propagation — avoid manual `match` on `Result` when `?` suffices
- Create domain-specific error enums with `#[derive(thiserror::Error)]`
- Use `Option<T>` for values that may not exist — never use sentinel values
- Chain with `.map()`, `.and_then()`, `.unwrap_or_default()` — avoid nested `match` blocks

### Unsafe Isolation
- **Minimize `unsafe` blocks** — wrap unsafe operations in safe abstractions
- Document every `unsafe` block with a `// SAFETY:` comment explaining why it's sound
- Never expose raw pointers in public APIs — wrap in safe types

### Code Quality
- Run `cargo clippy` — treat all warnings as errors
- Run `cargo fmt` — never deviate from project formatting
- Use `#[derive(Debug, Clone, PartialEq)]` on all data types unless there's a reason not to
- Prefer `impl Trait` in argument position over generic constraints when there's only one trait bound
- Use `#[must_use]` on functions that return values that shouldn't be ignored

### Patterns
- Use **builder pattern** for complex struct construction
- Use `enum` with variants for state machines — not boolean flags
- Prefer iterators and combinators (`.iter().map().filter().collect()`) over manual loops
- Use `Default` trait for structs with sensible defaults
- Use `From`/`Into` traits for type conversions — avoid custom conversion functions

### Naming Conventions
- `snake_case` for functions, methods, variables, modules
- `PascalCase` for types, traits, enums
- `UPPER_SNAKE_CASE` for constants and statics
- Prefix boolean methods with `is_`, `has_`, `can_`

### Testing Considerations
- Write code that is testable — use trait objects or generics for dependency injection
- Use `#[cfg(test)]` module for unit tests within the same file
- Prefer deterministic code — accept timestamps/randomness as parameters
