rust-patterns
Skill3 starsChanged 7 months agoMITView on GitHub
Rust best practices, patterns, and idioms. Covers ownership, error handling with Result/Option, traits, lifetimes, and async Rust. Use when writing Rust code or reviewing Rust patterns.
Files
Rust Patterns
Modern Rust patterns and best practices.
Error Handling
Custom Error Types with thiserror
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Unauthorized: {0}")]
Unauthorized(String),
#[error("Database error")]
Database(#[from] sqlx::Error),
#[error("IO error")]
Io(#[from] std::io::Error),
}Propagation with ?
fn read_config(path: &str) -> Result<Config, AppError> {
let content = std::fs::read_to_string(path)?; // Auto-converts io::Error
let config: Config = serde_json::from_str(&content)
.map_err(|e| AppError::NotFound(format!("Invalid config: {e}")))?;
Ok(config)
}Option Combinators
fn find_user(id: &str) -> Option<User> {
users.iter()
.find(|u| u.id == id)
.filter(|u| u.is_active)
.map(|u| u.clone())
}
// Chain with unwrap_or, unwrap_or_else, unwrap_or_default
let name = user.name.as_deref().unwrap_or("Anonymous");Ownership and Borrowing
Prefer Borrowing
// Good: Borrows data, doesn't take ownership
fn process(data: &[u8]) -> Result<Output, Error> { /* ... */ }
// Good: Mutable borrow when needed
fn update(config: &mut Config) { /* ... */ }
// Take ownership only when necessary (storing, sending to thread)
fn spawn_worker(data: Vec<u8>) { /* ... */ }Builder Pattern
pub struct ServerBuilder {
addr: String,
port: u16,
max_connections: Option<usize>,
}
impl ServerBuilder {
pub fn new(addr: impl Into<String>) -> Self {
Self {
addr: addr.into(),
port: 8080,
max_connections: None,
}
}
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
pub fn max_connections(mut self, max: usize) -> Self {
self.max_connections = Some(max);
self
}
pub fn build(self) -> Server {
Server { /* ... */ }
}
}
// Usage: Server::builder("localhost").port(3000).build()Traits
Define Behavior, Not Data
pub trait Repository {
type Error;
fn find_by_id(&self, id: &str) -> Result<Option<User>, Self::Error>;
fn save(&self, user: &User) -> Result<(), Self::Error>;
fn delete(&self, id: &str) -> Result<bool, Self::Error>;
}Blanket Implementations
// Implement for all types that satisfy bounds
impl<T: Display + Debug> Loggable for T {
fn log(&self) {
println!("[LOG] {self}");
}
}Async Rust
Tokio Patterns
use tokio::task::JoinSet;
async fn fetch_all(urls: Vec<String>) -> Vec<Result<Response, Error>> {
let mut set = JoinSet::new();
for url in urls {
set.spawn(async move {
reqwest::get(&url).await?.text().await
});
}
let mut results = Vec::new();
while let Some(result) = set.join_next().await {
results.push(result.unwrap());
}
results
}Graceful Shutdown
use tokio::signal;
async fn run_server() -> Result<(), Error> {
let server = start_server().await?;
signal::ctrl_c().await?;
println!("Shutting down...");
server.shutdown().await;
Ok(())
}Tooling
| Tool | Purpose | Command |
| cargo check | Type checking | cargo check |
| cargo clippy | Linting | cargo clippy -- -D warnings |
| cargo fmt | Formatting | cargo fmt -- --check |
| cargo test | Testing | cargo test |
| cargo audit | Security | cargo audit |
Checklist
clippypasses with no warnings- Error types defined with
thiserror ?operator for error propagation- Prefer borrowing over ownership transfer
Cloneonly when necessarySend + Syncbounds for async types- No
unwrap()in library code (use?orexpect) - Builder pattern for types with many options
Other versions22 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 22
- Cosmian/kms★ 362same name
- loulanyue/awesome-claude-notes★ 272same name
- FlorianBruniaux/ccboard★ 94same name
- Fmarzochi/EGC★ 61same name
- talayash/agentrium★ 47same name
- Bitslix/BLXCode★ 15same name
- gongyijie85/dsh-ecc★ 8same name
- aphrody-code/bxc★ 2same name
- idexal/idexal-skills★ 2same name
- lukemurraynz/hve-agent-skills★ 2same name
12 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.
Used alongsideProjects with it also use nuxt4-patterns, pytorch-patterns and 9 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.
loulanyueSkillnuxt4-patterns
Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.
Also in 5 projects that use this
Yog-SothoSkillpytorch-patterns
PyTorch deep learning patterns and best practices for building robust, efficient, and reproducible training pipelines, model architectures, and data loading. Always activate when the user is writing PyTorch models or training scripts, reviewing deep learning code, debugging training loops or data pipelines, optimizing GPU memory or training speed, setting up reproducible experiments, implementing transfer learning or fine-tuning, or asks anything about nn.Module, DataLoader, autograd, AMP, or torch.compile.
Also in 6 projects that use this
loulanyueSkillsafety-guard
Also in 4 projects that use this
xfstudioSkillarchitecture-decision-records
Write and maintain Architecture Decision Records (ADRs) following best practices for technical decision documentation. Use when documenting significant technical decisions, reviewing past architectural choices, or establishing decision processes.
Also in 7 projects that use this
get-proofpilotSkillcontext-budget
Audits Claude Code context window consumption across agents, skills, MCP servers, and rules. Identifies bloat, redundant components, and produces prioritized token-savings recommendations.
Also in 6 projects that use this
dcs-soniSkillcodebase-onboarding
Help developers understand unfamiliar codebases quickly. Use when
Also in 5 projects that use this
- +3 more from loulanyue
In this repository72 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- api-designerSkill
- backend-patternsSkill
- code-reviewerSkill
- debugging-assistantSkill
- golang-testingSkill
- project-guidelines-exampleSkill
- python-testingSkill
- refactoring-guideSkill
- spec-driven-developmentSkill
- tdd-workflowSkill
- verification-loopSkill
- update-docsSkill
- api-docsSkill
- changelog-writerSkill
- readme-generatorSkill
- django-patternsSkill
- django-securitySkill
- django-tddSkill
- django-verificationSkill
- fastapi-patternsSkill
- nextjs-patternsSkill
- react-patternsSkill
- springboot-patternsSkill
- springboot-securitySkill
- springboot-tddSkill
- branch-strategySkill
- changelogSkill
- commit-helperSkill
- pr-creatorSkill
- prSkill
- evolveSkill
- instinct-exportSkill
- instinct-importSkill
- instinct-statusSkill
- cleanupSkill
- lint-fixSkill
- refactor-cleanSkill
- update-depsSkill
- continuous-learningSkill
- continuous-learning-v2Skill
- eval-harnessSkill
- iterative-retrievalSkill
- strategic-compactSkill
- golang-patternsSkill
- python-patternsSkill
- typescript-patternsSkill
- accessibility-checkerSkill
- build-fixSkill
- code-reviewSkill
- e2eSkill
- performance-reviewerSkill
- security-auditorSkill
- security-reviewSkill
- test-coverageSkill
- checkpointSkill
- deploySkill
- evalSkill
- The first 60 shown.
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.

