agentleFS
medy-gribkovmedy-gribkov/arcana/skills/rust-best-practices/SKILL.md

rust-best-practices

Skill1 starsChanged 9 months agoApache-2.0View on GitHub

Idiomatic Rust development with ownership, borrowing, lifetimes, error handling (thiserror/anyhow), async Tokio patterns, traits, generics, Clippy linting, cargo workspaces, and production patterns for web services (axum/actix-web), CLI tools (clap), and systems programming. Use when writing, reviewing, or debugging Rust code.

24 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use inngest, go-best-practices and 8 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • xfstudioSkill

    inngest

    Inngest expert for serverless-first background jobs, event-driven workflows, and durable execution without managing queues or workers. Use when: inngest, serverless background job, event-driven workflow, step function, durable execution.

    Also in 3 projects that use this

  • mduongvandinhSkill

    go-best-practices

    Also in 3 projects that use this

  • xfstudioSkill

    rust-async-patterns

    Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.

    Also in 3 projects that use this

  • dbDev-codeSkill

    tauri-v2

    Tauri v2+ cross-platform app development with Rust backend. Use when configuring tauri.conf.json, implementing Rust commands (#[tauri::command]), setting up IPC patterns (invoke, emit, channels), configuring permissions/capabilities, troubleshooting build issues, or deploying desktop/mobile apps. Triggers on Tauri, src-tauri, invoke, emit, capabilities.json.

    Also in 3 projects that use this

  • VercelSkill

    vercel-react-best-practices

    React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

    Also in 6 projects that use this

  • VercelSkill

    agent-browser

    Automates browser interactions for web testing, form filling, screenshots, and data extraction. Use when the user needs to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

    Also in 6 projects that use this

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 2 are distinctive, and 8 are very specific to this project.

  • 0

    Common

    Most of the 23 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 8

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Lifetime annotations: - only needed when the compiler can't infer:

    line 32
  2. Very specific:

    Use thiserror for library crates (typed errors), anyhow for application crates (ergonomic propagation).

    line 90
  3. Very specific:

    Never use .unwrap() in production code: Use .expect("reason") only for truly impossible cases.

    line 117
  4. Very specific:

    Never call std::thread::sleep in async code.

    line 142
  5. Very specific:

    Never hold a MutexGuard (std or tokio) across an .await point.

    line 143
  6. Very specific:

    Use tokio::sync::Mutex only when you need to hold it across .await.

    line 144
  7. Distinctive:

    Extension traits: - add methods to foreign types:

    line 171
  8. Very specific:

    String types: Use &str for parameters, String for owned data.

    line 293
  9. Very specific:

    Not using #[must_use]: Add it to functions whose return value should never be ignored (especially Result).

    line 297
  10. Very specific:

    Large structs on the stack: If a struct is >1KB, Box it.

    line 298

“Common” is measured: kept by at least 6 in 10 of the 23 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

You are a Rust expert specializing in safe, performant, idiomatic Rust for production systems, web services, and CLI tooling.

Use this skill when

  • Writing or reviewing Rust code
  • Designing ownership/borrowing/lifetime strategies
  • Building async services with Tokio
  • Structuring cargo workspaces or crate architecture
  • Debugging borrow checker or lifetime errors

Ownership, Borrowing, and Lifetimes

The three rules that prevent 90% of borrow checker fights:

  1. Each value has exactly one owner. When the owner goes out of scope, the value is dropped.
  2. You can have either ONE mutable reference OR any number of immutable references (not both).
  3. References must always be valid (no dangling pointers).
// BAD: moving out of a vector element
let names = vec!["alice".to_string(), "bob".to_string()];
let first = names[0]; // ERROR: cannot move out of index

// GOOD: borrow or clone
let first = &names[0];       // borrow
let first = names[0].clone(); // clone if you need ownership

Lifetime annotations - only needed when the compiler can't infer:

// The compiler needs to know: does the return value live as long as `a` or `b`?
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}

// Struct holding a reference MUST declare the lifetime
struct Config<'a> {
    name: &'a str,
}

Lifetime scopes visualized:

┌─────────────────────────────────────────┐
│ fn example() {                          │
│   let owner = String::from("data");    │ ← 'owner lives here
│   ├─────────────────────────┐           │
│   │ let borrowed = &owner;  │           │ ← 'borrowed valid
│   │ println!("{borrowed}"); │           │   while owner alive
│   └─────────────────────────┘           │
│ } ← owner dropped, borrowed invalid     │
└─────────────────────────────────────────┘

Multiple borrows:
┌─────────────────────────────────────────┐
│ fn multi() {                            │
│   let mut data = vec![1, 2, 3];        │
│   ├───────────────────┐                 │
│   │ let r1 = &data;   │                 │ ← immutable borrows OK
│   │ let r2 = &data;   │                 │
│   │ println!("{r1}"); │                 │
│   └───────────────────┘                 │
│   ├───────────────────┐                 │
│   │ let r3 = &mut data; │               │ ← mutable borrow alone
│   │ r3.push(4);       │                 │
│   └───────────────────┘                 │
│ }                                       │
└─────────────────────────────────────────┘

Common pitfall - returning references to local data:

// BAD: returns reference to local String
fn bad() -> &str {
    let s = String::from("hello");
    &s // ERROR: `s` dropped here
}

// GOOD: return owned data
fn good() -> String {
    String::from("hello")
}

Error Handling

Use thiserror for library crates (typed errors), anyhow for application crates (ergonomic propagation).

// Library crate: thiserror
#[derive(Debug, thiserror::Error)]
pub enum AppError {
    #[error("database error: {0}")]
    Db(#[from] sqlx::Error),
    #[error("not found: {entity} with id {id}")]
    NotFound { entity: &'static str, id: i64 },
    #[error("validation failed: {0}")]
    Validation(String),
}

// Application crate: anyhow
use anyhow::{Context, Result};

async fn load_config(path: &str) -> Result<Config> {
    let contents = tokio::fs::read_to_string(path)
        .await
        .context("failed to read config file")?;
    let config: Config = toml::from_str(&contents)
        .context("failed to parse config TOML")?;
    Ok(config)
}

Never use .unwrap() in production code. Use .expect("reason") only for truly impossible cases. Prefer ? propagation everywhere else.

Async with Tokio

// Cargo.toml: tokio = { version = "1", features = ["full"] }

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Spawn concurrent tasks
    let (users, orders) = tokio::try_join!(
        fetch_users(),
        fetch_orders(),
    )?;

    // CPU-heavy work: use spawn_blocking, never block the async runtime
    let hash = tokio::task::spawn_blocking(move || {
        argon2::hash_password(&password)
    }).await??;

    Ok(())
}

Async pitfalls:

  • Never call std::thread::sleep in async code. Use tokio::time::sleep.
  • Never hold a MutexGuard (std or tokio) across an .await point.
  • Use tokio::sync::Mutex only when you need to hold it across .await. Otherwise std::sync::Mutex is faster.
  • Send + Sync bounds: if a future isn't Send, it can't be spawned with tokio::spawn. Common fix: drop non-Send types before .await.

Traits and Generics

// Define behavior with traits
trait Repository: Send + Sync {
    async fn find_by_id(&self, id: i64) -> Result<Option<User>>;
    async fn save(&self, user: &User) -> Result<()>;
}

// Use impl Trait for simple cases
fn process(items: &[impl AsRef<str>]) { /* ... */ }

// Use trait objects for dynamic dispatch (runtime polymorphism)
fn get_repo(config: &Config) -> Box<dyn Repository> {
    match config.db_type {
        DbType::Postgres => Box::new(PgRepo::new()),
        DbType::Sqlite => Box::new(SqliteRepo::new()),
    }
}

// Prefer generics (static dispatch) when performance matters
fn serialize<T: Serialize>(value: &T) -> Result<Vec<u8>> { /* ... */ }

Extension traits - add methods to foreign types:

trait StringExt {
    fn truncate_ellipsis(&self, max_len: usize) -> String;
}
impl StringExt for str {
    fn truncate_ellipsis(&self, max_len: usize) -> String {
        if self.len() <= max_len { return self.to_string(); }
        format!("{}...", &self[..max_len.saturating_sub(3)])
    }
}

Axum Web Service Pattern

use axum::{Router, Json, extract::{State, Path}, http::StatusCode};

#[derive(Clone)]
struct AppState {
    db: sqlx::PgPool,
}

async fn get_user(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(&state.db)
        .await?
        .ok_or(AppError::NotFound { entity: "user", id })?;
    Ok(Json(user))
}

fn app(state: AppState) -> Router {
    Router::new()
        .route("/users/{id}", axum::routing::get(get_user))
        .layer(tower_http::trace::TraceLayer::new_for_http())
        .layer(tower_http::cors::CorsLayer::permissive())
        .with_state(state)
}

CLI with Clap

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "mytool", version, about = "A production CLI")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
    #[arg(short, long, global = true, action = clap::ArgAction::Count)]
    verbose: u8,
}

#[derive(Subcommand)]
enum Commands {
    /// Run the migration
    Migrate {
        #[arg(short, long, default_value = "postgres://localhost/mydb")]
        database_url: String,
    },
    /// Check system health
    Health,
}

Clippy and Linting

# clippy.toml or .clippy.toml
avoid-breaking-exported-api = false

# Cargo.toml — deny warnings in CI
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "deny"
expect_used = "warn"
dbg_macro = "deny"
todo = "warn"

Run: cargo clippy --all-targets --all-features -- -D warnings

Key Clippy lints to always enable: unwrap_used, dbg_macro, print_stdout (for libraries), large_enum_variant (box variants >200 bytes), needless_pass_by_value.

Cargo Workspace Pattern

# Root Cargo.toml
[workspace]
members = ["crates/*"]
resolver = "2"

[workspace.package]
version = "0.1.0"
edition = "2024"

[workspace.dependencies]
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
anyhow = "1"
# crates/api/Cargo.toml
[package]
name = "myapp-api"
version.workspace = true
edition.workspace = true

[dependencies]
tokio.workspace = true
myapp-core = { path = "../core" }

Workspace layout: crates/core (domain logic, no IO), crates/api (HTTP layer), crates/cli (binary), crates/db (persistence). Core depends on nothing. API and CLI depend on core.

Common Pitfalls

  1. String types: Use &str for parameters, String for owned data. Never &String.
  2. Cloning to satisfy the borrow checker: Usually means your architecture needs rethinking. Try restructuring to avoid the need.
  3. Arc<Mutex<T>>: Fine for shared mutable state, but consider channels or dashmap for concurrent maps.
  4. .collect::<Vec<_>>() then iterate again: Chain iterators instead. Collect only at boundaries.
  5. Not using #[must_use]: Add it to functions whose return value should never be ignored (especially Result).
  6. Large structs on the stack: If a struct is >1KB, Box it. Check with std::mem::size_of.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.