---
description: "Rust coding conventions: error handling with Result/thiserror/anyhow, ownership patterns, clippy, module structure"
globs: ["**/*.rs", "**/Cargo.toml", "**/Cargo.lock"]
---
# Rust

- Use `Result<T, E>` for recoverable errors; `panic!` only for unrecoverable
- Use `?` operator for error propagation; define custom error types with `thiserror`; use `anyhow` for application-level errors
- Prefer references over cloning; minimize unnecessary allocations
- Never use `unwrap()` in production code; use `expect()` with descriptive message or proper error handling
- Minimize `unsafe`; document invariants when used; isolate in separate modules
- Use `Arc<Mutex<T>>` for shared mutable state; prefer channels (`mpsc`) for message passing
- Use `clippy` and `rustfmt`; treat clippy warnings as errors in CI
- Module structure: `src/main.rs` or `src/lib.rs` as entry; submodules in separate files
- Use `#[cfg(test)]` module for unit tests; `tests/` directory for integration tests
- Use feature flags for conditional compilation
- Use `serde` for serialization with `derive` feature
