CLAUDE.md

Rust Project Guidelines

Overview

Rust application following idiomatic patterns with a focus on safety, performance, and clarity.

Tech Stack

  • Language: Rust (latest stable)
  • Build: Cargo
  • Testing: Built-in test framework
  • Linting: Clippy
  • Formatting: rustfmt

Development Commands

# Build
cargo build

# Build release
cargo build --release

# Run
cargo run

# Run tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run clippy
cargo clippy

# Format code
cargo fmt

# Check without building
cargo check

# Generate docs
cargo doc --open

Project Structure

src/
├── main.rs        # Binary entrypoint
├── lib.rs         # Library entrypoint
├── config.rs      # Configuration
├── error.rs       # Error types
├── models/        # Data structures
├── handlers/      # Request handlers (for web)
├── services/      # Business logic
└── utils/         # Utilities
tests/             # Integration tests
benches/           # Benchmarks

Code Style

  • Follow Rust API Guidelines
  • Use rustfmt for formatting
  • Run clippy and fix all warnings
  • Document public APIs with doc comments
  • Use meaningful names

Error Handling

  • Use Result<T, E> for fallible functions
  • Create custom error types with thiserror
  • Use ? operator for error propagation
  • Provide context with anyhow or error wrapping
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("User not found: {0}")]
    UserNotFound(String),
    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),
}

Ownership and Borrowing

  • Prefer borrowing over ownership when possible
  • Use &str over String in function parameters
  • Use Clone only when necessary
  • Understand when to use Rc, Arc, RefCell

Patterns

  • Use enums with data for state machines
  • Implement traits for polymorphism
  • Use iterators and combinators
  • Prefer match over if let for exhaustiveness
  • Use Option and Result combinators

Testing

  • Write unit tests in the same file
  • Use #[cfg(test)] module
  • Write integration tests in tests/
  • Use test fixtures and helpers
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_something() {
        // test implementation
    }
}

Performance

  • Prefer stack allocation
  • Use &[T] over Vec<T> for read-only
  • Consider Cow<str> for flexible ownership
  • Profile before optimizing
  • Use release builds for benchmarks

Async (if applicable)

  • Use tokio or async-std runtime
  • Prefer async fn over manual futures
  • Handle cancellation properly
  • Use tokio::select! for concurrent operations