CLAUDE.md rules for Rust 2024 crates with borrow-first APIs, Cow, thiserror 2 typed errors kept apart from anyhow, sqlx lookups and non-blocking Tokio workers.
.claude/rules/claude-rust-developer.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# Rust Conventions
Applies to: Rust crates in this repository (libraries, services and CLIs), including async code on Tokio.
Version baseline: checked against Rust 1.85+ (2024 edition), thiserror 2, anyhow 1, Tokio 1 and sqlx 0.9. Read `Cargo.toml` (`edition`, `rust-version`, versions) and stay within the declared MSRV.
## Ownership and borrowing
- Borrow for read access (`&str`, `&[T]`), and borrow mutably for in-place changes (`&mut Vec<T>`).
- Take ownership only when the function stores or consumes the value.
- Use `Cow<'_, str>` when a function usually returns its input unchanged and only sometimes allocates.
- Avoid adding `.clone()`, `Rc<RefCell<_>>` or `Arc<Mutex<_>>` just to silence the borrow checker. Restructure first, and explain any shared mutable state you keep.
```rust
use std::borrow::Cow;
pub fn analyze(data: &[u8]) -> usize {
data.iter().filter(|&&b| b == b'\n').count()
}
pub fn drop_zeros(data: &mut Vec<u8>) {
data.retain(|&b| b != 0);
}
pub fn normalize(input: &str) -> Cow<'_, str> {
if input.contains("bad") {
Cow::Owned(input.replace("bad", "good"))
} else {
Cow::Borrowed(input) // no allocation when nothing changes
}
}
```
## Error handling
- Library and domain code returns a typed error enum built with `thiserror`. Application entry points (`main`, CLI commands, job runners) may use `anyhow::Result` and add `.context(...)`.
- Keep std `Result<T, E>` and `anyhow::Result<T>` visibly distinct. Don't import `anyhow::Result` into modules that define typed errors.
- Preserve the cause with `#[from]` or `#[source]`. Expected absence is `Option` or a `NotFound` variant, not a panic.
- No `unwrap()` on I/O, parsing or user input outside tests. `expect("invariant: ...")` documents a real invariant.
```rust
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("user not found: {0}")]
NotFound(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("database error")]
Database(#[from] sqlx::Error),
}
pub async fn get_user(pool: &sqlx::PgPool, id: &str) -> Result<User, AppError> {
sqlx::query_as::<_, User>("SELECT id, email FROM users WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?
.ok_or_else(|| AppError::NotFound(id.to_owned()))
}
```
(`User` derives `sqlx::FromRow`.)
## Async (Tokio)
- Don't block inside async code. Use async I/O, and run CPU-heavy or blocking calls with `tokio::task::spawn_blocking`.
- Use bounded channels so slow consumers apply backpressure. A worker loop ends when all senders are dropped.
- Report errors through `tracing` (or the project's logger), not `eprintln!`, so they carry context.
```rust
use tokio::sync::mpsc;
pub async fn worker(mut rx: mpsc::Receiver<Task>) {
while let Some(task) = rx.recv().await {
if let Err(e) = process_task(task).await {
tracing::warn!(error = %e, "task failed");
}
}
}
```
## unsafe and performance
- Use `unsafe` only when a safe alternative is impossible or measurably too slow. Each block needs a `// SAFETY:` comment and tests (run Miri where possible).
- Optimize only with a benchmark (`cargo bench`/criterion) showing the gain, and include the numbers in the summary.
## Verify before finishing
Run when available: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test`, and `cargo +nightly miri test` for crates containing `unsafe`.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.
CLAUDE.md rules for the Next.js 16 App Router with async params, streaming via Suspense, secured Server Actions, metadata conventions and explicit caching choices.
Claude
systems
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code edits a Rust service that uses Tokio and sqlx, with this file loaded as a project rule scoped to **/*.rs.
src/users.rs: get_user uses `use anyhow::Result;` but returns Result<User, AppError>, calls .unwrap() on fetch_optional, and the worker prints failures with eprintln!. Clean this up. Cargo.toml: edition 2024, thiserror 2, sqlx 0.9 (postgres), tokio 1, tracing 0.1.
Illustrative; not a recorded model run. The anyhow::Result import is removed from the typed-error module; get_user returns Result<User, AppError> using fetch_optional(...).await? with #[from] sqlx::Error and ok_or_else(NotFound); no unwrap; the worker logs with tracing::warn!(error = %e); no new clones or Arc<Mutex> added; clippy -D warnings and cargo test results reported.
Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-rust-developer.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# Rust Conventions
Applies to: Rust crates in this repository (libraries, services and CLIs), including async code on Tokio.
Version baseline: checked against Rust 1.85+ (2024 edition), thiserror 2, anyhow 1, Tokio 1 and sqlx 0.9. Read `Cargo.toml` (`edition`, `rust-version`, versions) and stay within the declared MSRV.
## Ownership and borrowing
- Borrow for read access (`&str`, `&[T]`), and borrow mutably for in-place changes (`&mut Vec<T>`).
- Take ownership only when the function stores or consumes the value.
- Use `Cow<'_, str>` when a function usually returns its input unchanged and only sometimes allocates.
- Avoid adding `.clone()`, `Rc<RefCell<_>>` or `Arc<Mutex<_>>` just to silence the borrow checker. Restructure first, and explain any shared mutable state you keep.
```rust
use std::borrow::Cow;
pub fn analyze(data: &[u8]) -> usize {
data.iter().filter(|&&b| b == b'\n').count()
}
pub fn drop_zeros(data: &mut Vec<u8>) {
data.retain(|&b| b != 0);
}
pub fn normalize(input: &str) -> Cow<'_, str> {
if input.contains("bad") {
Cow::Owned(input.replace("bad", "good"))
} else {
Cow::Borrowed(input) // no allocation when nothing changes
}
}
```
## Error handling
- Library and domain code returns a typed error enum built with `thiserror`. Application entry points (`main`, CLI commands, job runners) may use `anyhow::Result` and add `.context(...)`.
- Keep std `Result<T, E>` and `anyhow::Result<T>` visibly distinct. Don't import `anyhow::Result` into modules that define typed errors.
- Preserve the cause with `#[from]` or `#[source]`. Expected absence is `Option` or a `NotFound` variant, not a panic.
- No `unwrap()` on I/O, parsing or user input outside tests. `expect("invariant: ...")` documents a real invariant.
```rust
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("user not found: {0}")]
NotFound(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("database error")]
Database(#[from] sqlx::Error),
}
pub async fn get_user(pool: &sqlx::PgPool, id: &str) -> Result<User, AppError> {
sqlx::query_as::<_, User>("SELECT id, email FROM users WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?
.ok_or_else(|| AppError::NotFound(id.to_owned()))
}
```
(`User` derives `sqlx::FromRow`.)
## Async (Tokio)
- Don't block inside async code. Use async I/O, and run CPU-heavy or blocking calls with `tokio::task::spawn_blocking`.
- Use bounded channels so slow consumers apply backpressure. A worker loop ends when all senders are dropped.
- Report errors through `tracing` (or the project's logger), not `eprintln!`, so they carry context.
```rust
use tokio::sync::mpsc;
pub async fn worker(mut rx: mpsc::Receiver<Task>) {
while let Some(task) = rx.recv().await {
if let Err(e) = process_task(task).await {
tracing::warn!(error = %e, "task failed");
}
}
}
```
## unsafe and performance
- Use `unsafe` only when a safe alternative is impossible or measurably too slow. Each block needs a `// SAFETY:` comment and tests (run Miri where possible).
- Optimize only with a benchmark (`cargo bench`/criterion) showing the gain, and include the numbers in the summary.
## Verify before finishing
Run when available: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test`, and `cargo +nightly miri test` for crates containing `unsafe`.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
CLAUDE.md rules for React 19 with TypeScript covering typed components, derived state, compiler-aware memoization, useId-based accessibility and review checks.
CLAUDE.md rules for the Next.js 16 App Router with async params, streaming via Suspense, secured Server Actions, metadata conventions and explicit caching choices.