Rust best practices

From erikstmartin/dotfiles · View interactive version

Rust best practices is an AI agent skill from the GitHub repository erikstmartin/dotfiles. Use when writing or refactoring Rust for idioms, ownership/borrowing choices, Result-based error handling, performance, and tests/docs.

How to use this skill

Skill file

Rust Best Practices

Apply these guidelines when writing or reviewing Rust code.

Quick Reference

Borrowing & Ownership

Error Handling

Performance

Linting

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

Key lints to watch:

Use #[expect(clippy::lint)] over #[allow(...)] with justification comment.

Testing

Generics & Dispatch

Type State Pattern

Encode valid states in the type system to catch invalid operations at compile time:

struct Connection<State> { /* ... */ _state: PhantomData<State> }
struct Disconnected;
struct Connected;

impl Connection<Connected> {
    fn send(&self, data: &[u8]) { /* only connected can send */ }
}

Error Handling Example

use thiserror::Error;

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

pub fn find_user(id: &str) -> Result<User, AppError> {
    let user = db::query_user(id)?;  // ? auto-converts sqlx::Error via #[from]
    user.ok_or_else(|| AppError::NotFound {
        entity: "user",
        id: id.to_string(),
    })
}

#[from] on a variant generates a From<sqlx::Error> impl so ? converts automatically. Use anyhow::Error in main or CLI entry points where you want a catch-all with context chaining (context()/with_context()), and thiserror everywhere you expose errors to callers.

Documentation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.