Cursor rules for Rust systems code: borrowing-first APIs, thiserror/anyhow error layers, Tokio async with correct mutex choice, allocation-aware performance and project layout.
.cursor/rules/rust-systems-programming.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Rust systems code: borrowing-first APIs, thiserror/anyhow error layers, Tokio async with correct mutex choice, allocation-aware performance and project layout."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing Rust systems and service code.
## Ownership and borrowing
```rust
use std::borrow::Cow;
// Borrow when you only read
fn checksum(data: &[u8]) -> u32 {
data.iter().fold(0u32, |acc, b| acc.wrapping_add(u32::from(*b)))
}
// Take &mut when you modify in place
fn append_terminator(buf: &mut Vec<u8>) {
buf.push(0);
}
// Cow when you usually return the input unchanged
fn redact(input: &str) -> Cow<'_, str> {
if input.contains("password=") {
Cow::Owned(input.replace("password=", "password=***"))
} else {
Cow::Borrowed(input)
}
}
```
## Error handling
- Libraries and module boundaries: typed errors with `thiserror`, so callers can match on variants.
- Binaries: `anyhow::Result` with `.context(...)` at each layer.
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StoreError {
#[error("database error")]
Database(#[from] sqlx::Error),
#[error("user {0} not found")]
NotFound(String),
}
pub async fn get_user(pool: &sqlx::PgPool, id: &str) -> Result<User, StoreError> {
sqlx::query_as::<_, User>("SELECT id, email FROM users WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?
.ok_or_else(|| StoreError::NotFound(id.to_owned()))
}
fn load_config(path: &std::path::Path) -> anyhow::Result<Config> {
use anyhow::Context;
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading {}", path.display()))?;
toml::from_str(&text).context("parsing config")
}
```
## Async
- Use Tokio for async services. Share state through `Arc<AppState>`; put a `std::sync::Mutex` around data that is locked briefly, and use `tokio::sync::Mutex` only when a guard must be held across `.await`.
- Use bounded `mpsc` channels between tasks, `JoinSet` to track spawned tasks, and `spawn_blocking` for blocking work.
```rust
use std::{collections::HashMap, sync::{Arc, Mutex}};
struct AppState {
db: sqlx::PgPool,
cache: Mutex<HashMap<String, String>>, // locked briefly, never across .await
}
async fn handle(state: Arc<AppState>, key: String) -> anyhow::Result<Option<String>> {
if let Some(hit) = state.cache.lock().unwrap().get(&key).cloned() {
return Ok(Some(hit));
}
let row: Option<(String,)> = sqlx::query_as("SELECT value FROM kv WHERE key = $1")
.bind(&key)
.fetch_optional(&state.db)
.await?;
if let Some((value,)) = &row {
state.cache.lock().unwrap().insert(key, value.clone());
}
Ok(row.map(|(v,)| v))
}
```
## Performance
- Measure first: benchmarks with `criterion`, profiles with `perf`/`cargo flamegraph` or the platform profiler.
- Prefer iterators and slices; avoid allocating in hot loops (`Vec::with_capacity` when the size is known, reuse buffers).
- Return borrowed slices (`&str`, `&[T]`) when the result is part of the input.
- Run `cargo clippy` and `cargo fmt` before proposing changes.
## Project structure
```
src/
├── main.rs # binary entry: config, logging, runtime
├── lib.rs # library root; most logic lives here so it can be tested
├── config.rs
├── error.rs
├── db/
│ ├── mod.rs
│ └── models.rs
├── api/
│ ├── mod.rs
│ └── handlers.rs
└── services/
└── mod.rs
```
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
systems
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Tokio + sqlx service caches lookups in Arc<tokio::sync::Mutex<HashMap>> and returns String errors from its repository layer.
Using the Rust Systems Programming rule, refactor src/services/kv.rs and src/db/mod.rs. Keep the public HTTP API unchanged.
Repository functions return a thiserror enum (Database #[from] sqlx::Error, NotFound), the binary uses anyhow with context, the cache uses std::sync::Mutex with guards dropped before any .await, and the change notes that cargo clippy and cargo test should be run.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/rust-systems-programming.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Rust Systems Programming project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing Rust systems and service code.
## Ownership and borrowing
```rust
use std::borrow::Cow;
// Borrow when you only read
fn checksum(data: &[u8]) -> u32 {
data.iter().fold(0u32, |acc, b| acc.wrapping_add(u32::from(*b)))
}
// Take &mut when you modify in place
fn append_terminator(buf: &mut Vec<u8>) {
buf.push(0);
}
// Cow when you usually return the input unchanged
fn redact(input: &str) -> Cow<'_, str> {
if input.contains("password=") {
Cow::Owned(input.replace("password=", "password=***"))
} else {
Cow::Borrowed(input)
}
}
```
## Error handling
- Libraries and module boundaries: typed errors with `thiserror`, so callers can match on variants.
- Binaries: `anyhow::Result` with `.context(...)` at each layer.
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StoreError {
#[error("database error")]
Database(#[from] sqlx::Error),
#[error("user {0} not found")]
NotFound(String),
}
pub async fn get_user(pool: &sqlx::PgPool, id: &str) -> Result<User, StoreError> {
sqlx::query_as::<_, User>("SELECT id, email FROM users WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?
.ok_or_else(|| StoreError::NotFound(id.to_owned()))
}
fn load_config(path: &std::path::Path) -> anyhow::Result<Config> {
use anyhow::Context;
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading {}", path.display()))?;
toml::from_str(&text).context("parsing config")
}
```
## Async
- Use Tokio for async services. Share state through `Arc<AppState>`; put a `std::sync::Mutex` around data that is locked briefly, and use `tokio::sync::Mutex` only when a guard must be held across `.await`.
- Use bounded `mpsc` channels between tasks, `JoinSet` to track spawned tasks, and `spawn_blocking` for blocking work.
```rust
use std::{collections::HashMap, sync::{Arc, Mutex}};
struct AppState {
db: sqlx::PgPool,
cache: Mutex<HashMap<String, String>>, // locked briefly, never across .await
}
async fn handle(state: Arc<AppState>, key: String) -> anyhow::Result<Option<String>> {
if let Some(hit) = state.cache.lock().unwrap().get(&key).cloned() {
return Ok(Some(hit));
}
let row: Option<(String,)> = sqlx::query_as("SELECT value FROM kv WHERE key = $1")
.bind(&key)
.fetch_optional(&state.db)
.await?;
if let Some((value,)) = &row {
state.cache.lock().unwrap().insert(key, value.clone());
}
Ok(row.map(|(v,)| v))
}
```
## Performance
- Measure first: benchmarks with `criterion`, profiles with `perf`/`cargo flamegraph` or the platform profiler.
- Prefer iterators and slices; avoid allocating in hot loops (`Vec::with_capacity` when the size is known, reuse buffers).
- Return borrowed slices (`&str`, `&[T]`) when the result is part of the input.
- Run `cargo clippy` and `cargo fmt` before proposing changes.
## Project structure
```
src/
├── main.rs # binary entry: config, logging, runtime
├── lib.rs # library root; most logic lives here so it can be tested
├── config.rs
├── error.rs
├── db/
│ ├── mod.rs
│ └── models.rs
├── api/
│ ├── mod.rs
│ └── handlers.rs
└── services/
└── mod.rs
```
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.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.