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
- crbnos/carbontheir own version, first seen Oct 4, 2026
- baekenough/oh-my-customcodetheir own version, first seen Oct 3, 2026
- microsoft/scopetheir own version, first seen Sep 23, 2026
- meowdiocre/meowpitheir own version, first seen Sep 19, 2026
- massimodeluisa/rust-best-practices-skilltheir own version, first seen Sep 16, 2026
- BigtoC/my-skillstheir own version, first seen Sep 15, 2026
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.
xfstudioSkillinngest
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
mduongvandinhSkillgo-best-practices
Also in 3 projects that use this
xfstudioSkillrust-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-codeSkilltauri-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
VercelSkillvercel-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
VercelSkillagent-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
Other versions24 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 24
- crbnos/carbon★ 2.7ksame name
- pedronauck/skills★ 633same name
- apollographql/skills★ 116same name
- baekenough/oh-my-customcode★ 43same name
- ryo-ebata/cc-audit★ 25same name
- mduongvandinh/ai-best-practices-skills★ 18same name
- idexal/idexal-skills★ 13same name
- KalarisLabs/Skill-Doctor★ 13same name
- Harmeet10000/skills★ 7same name
- microsoft/scope★ 7same name
14 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository73 other files it gives its agents.
- accessibility-wcagSkill
- api-designSkill
- api-testingSkill
- asset-optimizationSkill
- audio-systemsSkill
- aws-essentialsSkill
- ci-cd-pipelinesSkill
- codebase-analysisSkill
- code-reviewerSkill
- container-securitySkill
- cost-optimizationSkill
- database-designSkill
- data-visualizationSkill
- doc-generationSkill
- docker-kubernetesSkill
- docxSkill
- email-notificationsSkill
- env-configSkill
- flutter-mobileSkill
- framer-motionSkill
- frontend-code-reviewSkill
- frontend-designSkill
- fullstack-developerSkill
- game-enginesSkill
- gameplay-designSkill
- game-programming-languagesSkill
- game-serversSkill
- git-workflowSkill
- godot-4Skill
- golang-proSkill
- go-linter-configurationSkill
- graphics-renderingSkill
- i18n-localizationSkill
- incident-responseSkill
- level-designSkill
- llm-integrationSkill
- local-securitySkill
- memory-managementSkill
- monetization-systemsSkill
- monitoring-observabilitySkill
- multiplayer-netcodeSkill
- nextjs-16Skill
- notebooklm-researchSkill
- npm-packageSkill
- oauth-authSkill
- particle-systemsSkill
- performance-optimizationSkill
- playwright-testingSkill
- postgres-advancedSkill
- programming-architectureSkill
- project-migrationSkill
- publishing-platformsSkill
- python-best-practicesSkill
- react-nativeSkill
- redis-patternsSkill
- refactoring-patternsSkill
- remotion-best-practicesSkill
- scraping-automationSkill
- security-reviewSkill
- seo-metaSkill
- The first 60 shown.
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
- Distinctive: line 32
Lifetime annotations: - only needed when the compiler can't infer:
- Very specific: line 90
Use thiserror for library crates (typed errors), anyhow for application crates (ergonomic propagation).
- Very specific: line 117
Never use
.unwrap()in production code: Use .expect("reason") only for truly impossible cases. - Very specific: line 142
Never call std::thread::sleep in async code.
- Very specific: line 143
Never hold a MutexGuard (std or tokio) across an .await point.
- Very specific: line 144
Use tokio::sync::Mutex only when you need to hold it across .await.
- Distinctive: line 171
Extension traits: - add methods to foreign types:
- Very specific: line 293
String types: Use &str for parameters, String for owned data.
- Very specific: line 297
Not using
#[must_use]: Add it to functions whose return value should never be ignored (especially Result). - Very specific: line 298
Large structs on the stack: If a struct is >1KB, Box it.
“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.
Files
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:
- Each value has exactly one owner. When the owner goes out of scope, the value is dropped.
- You can have either ONE mutable reference OR any number of immutable references (not both).
- 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 ownershipLifetime 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::sleepin async code. Usetokio::time::sleep. - Never hold a
MutexGuard(std or tokio) across an.awaitpoint. - Use
tokio::sync::Mutexonly when you need to hold it across.await. Otherwisestd::sync::Mutexis faster. Send + Syncbounds: if a future isn'tSend, it can't be spawned withtokio::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
- String types: Use
&strfor parameters,Stringfor owned data. Never&String. - Cloning to satisfy the borrow checker: Usually means your architecture needs rethinking. Try restructuring to avoid the need.
Arc<Mutex<T>>: Fine for shared mutable state, but consider channels ordashmapfor concurrent maps..collect::<Vec<_>>()then iterate again: Chain iterators instead. Collect only at boundaries.- Not using
#[must_use]: Add it to functions whose return value should never be ignored (especiallyResult). - Large structs on the stack: If a struct is >1KB,
Boxit. Check withstd::mem::size_of.
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
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.

