Rust Developer Guide
Purpose
Provides comprehensive Rust development best practices learned from 6 months of code reviews across the Catalyst project. Helps avoid common mistakes, write idiomatic Rust, and build safe, performant production code.
When to Use This Skill
Automatically activates when you:
- •Write or modify Rust code (
.rsfiles) - •Debug Rust compiler errors or warnings
- •Review Rust pull requests
- •Ask about Rust best practices
- •Implement CLI tools or hooks
- •Work with error handling, file I/O, or type safety
- •Optimize Rust code for performance
- •Question Rust patterns or idioms
Quick Start
New to Rust or this codebase? Start with Quick Reference Checklist - Scannable checklist of all 20+ rules
Working on specific topic? Jump to the relevant resource file below
Made a specific mistake? Check Common Footguns
Writing production code? Review Error Handling Deep Dive first
Resource Files
Quick Reference (Start Here)
quick-reference.md - 400-line scannable checklist
- •All 20+ lessons in one place
- •Rule + Quick check + Example + Link to deep dive
- •Perfect for code review or quick lookup
- •Can be scanned in under 2 minutes
Additional Patterns
rust-patterns.md - ~555 lines
When to use:
- •Choosing between thiserror and anyhow
- •Input validation at boundaries
- •Concurrent database access
- •Preventing SQL injection
- •Ownership patterns (borrow vs owned)
- •Testing error paths
Topics covered:
- •thiserror vs anyhow (when to use each)
- •Input validation with validator crate
- •Arc<Mutex<T>> for thread-safe shared state
- •Parameterized queries for SQL injection prevention
- •Ownership patterns (borrow params, return owned)
- •Testing error paths explicitly
- •Match-based error classification
Skill level: Intermediate
Complements: Error Handling, Type Safety, Common Footguns
Deep-Dive Guides (Comprehensive Learning)
1. Fundamentals
fundamentals-deep-dive.md - ~450 lines
When to use:
- •Setting up a new Rust project
- •Organizing imports and dependencies
- •Setting up tracing/logging
- •First-time Rust contributor
Topics covered:
- •Imports and code organization
- •Tracing subscribers (avoid duplicated setup)
- •CLI user feedback patterns
- •TTY detection for colored output
- •Avoiding duplicated logic
Skill level: Beginner
2. Error Handling
error-handling-deep-dive.md - ~600 lines
When to use:
- •Using
Option<T>orResult<T, E> - •Deciding between
unwrap(),expect(), and? - •Path operations that can fail
- •Converting between error types
Topics covered:
- •Option handling patterns (unwrap_or, unwrap_or_else, map_or)
- •Result handling and error propagation
- •When to use expect() vs unwrap() vs ?
- •Path operation footguns (display().to_string())
- •Context with anyhow or thiserror
Skill level: Beginner/Intermediate
3. File I/O Safety
file-io-deep-dive.md - ~500 lines
When to use:
- •Writing files (especially config/state files)
- •Creating directories
- •Working with temporary files
- •Testing file operations
Topics covered:
- •Atomic file writes with tempfile crate
- •Parent directory creation patterns
- •NamedTempFile usage
- •Testing file I/O (in-memory, temp dirs)
- •Avoiding TOCTOU races
Skill level: Intermediate
4. Type Safety
type-safety-deep-dive.md - ~650 lines
When to use:
- •Validating string inputs
- •Designing APIs with constrained values
- •Providing user-friendly error messages
- •Converting magic strings to types
Topics covered:
- •Constants → Enums progression
- •Newtype pattern for preventing type confusion
- •Validation at boundaries
- •User-friendly error messages
- •"Did you mean?" suggestions with edit distance
- •Pattern matching for exhaustiveness
Skill level: Intermediate
5. Performance Optimization
performance-deep-dive.md - ~450 lines
When to use:
- •Optimizing hot paths
- •Processing large datasets
- •Reducing allocations
- •Profiling performance bottlenecks
Topics covered:
- •Loop optimizations (pre-allocation, iteration patterns)
- •Zero-copy abstractions (AsRef, Borrow, Cow)
- •Pre-compilation patterns (static regexes, lazy_static)
- •Performance profiling tools
- •Benchmarking with criterion
Skill level: Intermediate/Advanced
6. Common Footguns
common-footguns.md - ~400 lines
When to use:
- •Debugging borrow checker errors
- •Path operation failures
- •Race conditions in file operations
- •Unexpected behavior in production
Topics covered:
- •Path operations (display().to_string() vs to_path_buf())
- •TOCTOU (Time-of-Check-Time-of-Use) races
- •Borrow checker with HashSet and collections
- •Common pitfalls and how to avoid them
Skill level: Mixed (Beginner through Advanced)
Learning Paths
Path 1: Beginner (First PRs)
Recommended reading order for new Rust developers:
- •
- •Imports and code organization
- •Tracing subscribers
- •Avoiding duplicated logic
- •
Error Handling (Sections 1-2)
- •Option handling basics
- •When to use expect vs unwrap
- •
- •Scan all rules to build awareness
Goal: Avoid the most common beginner mistakes
Path 2: Intermediate (Production Code)
For developers writing production-quality Rust:
- •
Error Handling (Complete)
- •All Option/Result patterns
- •Path operation footguns
- •
Rust Patterns (NEW!)
- •thiserror vs anyhow
- •Input validation
- •Ownership patterns
- •Arc<Mutex<T>> for concurrency
- •SQL injection prevention
- •Testing error paths
- •
- •Atomic writes
- •Safe file operations
- •Testing file I/O
- •
- •Constants → Enums progression
- •Validation patterns
- •User-friendly errors
- •
- •TOCTOU races
- •Borrow checker patterns
Goal: Write robust, safe production code
Path 3: Advanced (Performance & Safety)
For optimizing critical code paths:
- •
- •Loop optimizations
- •Zero-copy abstractions
- •Profiling techniques
- •
- •Borrow checker with collections
- •Advanced safety patterns
- •
Review all deep-dives for edge cases
Goal: Maximize performance while maintaining safety
Code Review Checklist
When reviewing Rust PRs, check against:
- •Quick Reference - All 20+ rules
- •Error Handling - Are Options/Results handled safely?
- •File I/O - Are writes atomic? Are parent dirs created?
- •Type Safety - Are magic strings replaced with enums?
- •Performance - Are hot paths optimized? Pre-allocated?
- •Common Footguns - Any TOCTOU races? Path operations safe?
Quick Topic Lookup
| Topic | Resource |
|---|---|
| anyhow vs thiserror | Rust Patterns |
| Arc<Mutex<T>> Pattern | Rust Patterns |
| Atomic File Writes | File I/O Deep Dive |
| Borrow Checker Issues | Common Footguns |
| CLI User Feedback | Fundamentals |
| Concurrent Database Access | Rust Patterns |
| Error Classification | Rust Patterns |
| Error Handling Patterns | Error Handling Deep Dive |
| Enums vs Strings | Type Safety Deep Dive |
| expect() vs unwrap() | Error Handling Deep Dive |
| Newtype Pattern | Type Safety Deep Dive |
| Input Validation | Rust Patterns |
| Loop Optimizations | Performance Deep Dive |
| Option Handling | Error Handling Deep Dive |
| Ownership Patterns | Rust Patterns |
| Path Operations | Common Footguns |
| Performance Profiling | Performance Deep Dive |
| SQL Injection Prevention | Rust Patterns |
| Testing Error Paths | Rust Patterns |
| TOCTOU Races | Common Footguns |
| Tracing Setup | Fundamentals |
| Validation Patterns | Type Safety Deep Dive |
Catalyst-Specific Patterns
Project Structure
catalyst/
├── catalyst-core/ # Core library (shared logic)
│ ├── src/
│ │ └── lib.rs
│ └── Cargo.toml
└── catalyst-cli/ # CLI binaries (hooks, tools)
├── src/bin/
│ ├── file_analyzer.rs
│ ├── skill_activation_prompt.rs
│ └── settings_manager.rs
└── Cargo.toml
Common Patterns in This Project
Binary Structure:
use thiserror::Error;
use tracing::{debug, error};
#[derive(Error, Debug)]
enum MyError {
#[error("[CODE] {message}\n{context}")]
SomeError { message: String, context: String },
}
fn run() -> Result<(), MyError> {
// Initialize tracing (do once in main, not in libraries)
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
// Business logic here
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("Error: {}", e);
std::process::exit(1);
}
}
Custom Error Types with thiserror:
#[derive(Error, Debug)]
enum ToolError {
#[error("[ERR001] File not found: {}\nTry: touch {}", path.display(), path.display())]
FileNotFound { path: PathBuf },
#[error("[ERR002] {0}")]
Io(#[from] std::io::Error),
}
Structured Logging:
error!(
error_code = "ERR001",
error_kind = "FileNotFound",
path = %path.display(),
"File operation failed"
);
Integration with Catalyst Workflow
When This Skill Activates
This skill automatically activates when:
- •
File Triggers:
- •Editing any
.rsfile in the project - •Creating new Rust binaries or libraries
- •Modifying
Cargo.tomlfiles
- •Editing any
- •
Prompt Triggers:
- •Mentioning "Rust", "cargo", "rustc"
- •Asking about error handling, Option, Result
- •Discussing performance optimizations
- •Requesting code reviews for Rust
- •
Content Triggers:
- •Code contains Rust-specific patterns (Result, Option, impl, trait)
- •Working with thiserror, anyhow, serde
- •Using Rust ecosystem crates
Complementary Skills
This skill works well with:
- •skill-developer - When creating new skills in Rust
- •error-tracking - When integrating Sentry (though we don't use it for Rust yet)
Contributing New Lessons
Found a new Rust footgun or best practice? See:
CONTRIBUTING.md - Complete guide for adding lessons
Quick steps:
- •Add to appropriate deep-dive guide
- •Update quick-reference.md
- •Maintain cross-references
- •Include before/after examples
Version History
Current Version: 1.0 Based on: Rust Lessons Learned v2.0 (6 months of code reviews, Phases 0-2.6) Last Updated: 2025-11-02 Maintainer: Catalyst Project Team
Quick Links
- •🚀 Quick Reference Checklist - Start here
- •📚 All Deep-Dive Guides - Comprehensive learning
- •🔍 Common Footguns - Avoid mistakes
- •📖 Navigation Guide - Full documentation index
Ready to write better Rust? Start with the Quick Reference →