Pins this version in aipm.package.json and aipm-lock.json.
aipm add @affaan-m/rust-patterns@1.0.0
Without project tracking
Writes the skill files only. Add --no-init to skip aipm.package.json and the lockfile.
aipm add @affaan-m/rust-patterns@1.0.0 --no-init
How to use
Install the skill above, then run this in your AI tool:
/rust-patterns <your description>
About
Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications. Use when writing or reviewing Rust code and ownership, error handling, traits, or concurrency is in q...
Skill instructions
Rust Development Patterns
Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
When to Use
Writing new Rust code
Reviewing Rust code
Refactoring existing Rust code
Designing crate structure and module layout
How It Works
This skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, Result/? error propagation with thiserror for libraries and anyhow for applications, enums and exhaustive pattern matching to make illegal states unrepresentable, traits and generics for zero-cost abstraction, safe concurrency via Arc<Mutex<T>>, channels, and async/await, and minimal pub surfaces organized by domain.
Core Principles
1. Ownership and Borrowing
Rust's ownership system prevents data races and memory bugs at compile time.
rust
// Good: Pass references when you don't need ownershipfnprocess(data: &[u8]) ->usize {
data.len()
}
// Good: Take ownership only when you need to store or consumefnstore(data: Vec<u8>) -> Record {
Record { payload: data }
}
// Bad: Cloning unnecessarily to avoid borrow checkerfnprocess_bad(data: &Vec<u8>) ->usize {
letcloned = data.clone(); // Wasteful — just borrow
cloned.len()
}
Use Cow for Flexible Ownership
rust
use std::borrow::Cow;
fnnormalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input) // Zero-cost when no mutation needed
}
}
Error Handling
Use Result and ? — Never unwrap() in Production
rust
// Good: Propagate errors with contextuse anyhow::{Context, Result};
fnload_config(path: &str) ->Result<Config> {
letcontent = std::fs::read_to_string(path)
.with_context(|| format!("failed to read config from {path}"))?;
letconfig: Config = toml::from_str(&content)
.with_context(|| format!("failed to parse config from {path}"))?;
Ok(config)
}
// Bad: Panics on errorfnload_config_bad(path: &str) -> Config {
letcontent = std::fs::read_to_string(path).unwrap(); // Panics!
toml::from_str(&content).unwrap()
}
Library Errors with thiserror, Application Errors with anyhow
// Use when you need heterogeneous collections or plugin systemstraitHandler: Send + Sync {
fnhandle(&self, request: &Request) -> Response;
}
structRouter {
handlers: Vec<Box<dyn Handler>>,
}
// Use generics when you need performance (monomorphization)fnfast_process<H: Handler>(handler: &H, request: &Request) -> Response {
handler.handle(request)
}
Newtype Pattern for Type Safety
rust
// Good: Distinct types prevent mixing up argumentsstructUserId(u64);
structOrderId(u64);
fnget_order(user: UserId, order: OrderId) ->Result<Order> {
// Can't accidentally swap user and order IDs
todo!()
}
// Bad: Easy to swap argumentsfnget_order_bad(user_id: u64, order_id: u64) ->Result<Order> {
todo!()
}
// Acceptable: FFI boundary with documented invariants (Rust 2024+)/// # Safety/// `ptr` must be a valid, aligned pointer to an initialized `Widget`.unsafefnwidget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
// SAFETY: caller guarantees ptr is valid and alignedunsafe { &*ptr }
}
// Acceptable: Performance-critical path with proof of correctness// SAFETY: index is always < len due to the loop boundunsafe { slice.get_unchecked(index) }
When Unsafe Is NOT Acceptable
rust
// Bad: Using unsafe to bypass borrow checker// Bad: Using unsafe for convenience// Bad: Using unsafe without a Safety comment// Bad: Transmuting between unrelated types
// Good: pub(crate) for internal sharingpub(crate) fnvalidate_input(input: &str) ->bool {
!input.is_empty()
}
// Good: Re-export public API from lib.rspubmod auth;
pubuse auth::AuthMiddleware;
// Bad: Making everything pubpubfninternal_helper() {} // Should be pub(crate) or private
Tooling Integration
Essential Commands
bash
# Build and check
cargo build
cargo check # Fast type checking without codegen
cargo clippy # Lints and suggestions
cargo fmt# Format code# Testing
cargo test
cargo test -- --nocapture # Show println output
cargo test --lib # Unit tests only
cargo test --test integration # Integration tests only# Dependencies
cargo audit # Security audit
cargo tree # Dependency tree
cargo update # Update dependencies# Performance
cargo bench # Run benchmarks
Quick Reference: Rust Idioms
Idiom
Description
Borrow, don't clone
Pass &T instead of cloning unless ownership is needed
Make illegal states unrepresentable
Use enums to model valid states only
? over unwrap()
Propagate errors, never panic in library/production code
Parse, don't validate
Convert unstructured data to typed structs at the boundary
Newtype for type safety
Wrap primitives in newtypes to prevent argument swaps
Prefer iterators over loops
Declarative chains are clearer and often faster
#[must_use] on Results
Ensure callers handle return values
Cow for flexible ownership
Avoid allocations when borrowing suffices
Exhaustive matching
No wildcard _ for business-critical enums
Minimal pub surface
Use pub(crate) for internal APIs
Anti-Patterns to Avoid
rust
// Bad: .unwrap() in production codeletvalue = map.get("key").unwrap();
// Bad: .clone() to satisfy borrow checker without understanding whyletdata = expensive_data.clone();
process(&original, &data);
// Bad: Using String when &str sufficesfngreet(name: String) { /* should be &str */ }
// Bad: Box<dyn Error> in libraries (use thiserror instead)fnparse(input: &str) ->Result<Data, Box<dyn std::error::Error>> { todo!() }
// Bad: Ignoring must_use warningslet_ = validate(input); // Silently discarding a Result// Bad: Blocking in async contextasyncfnbad_async() {
std::thread::sleep(Duration::from_secs(1)); // Blocks the executor!// Use: tokio::time::sleep(Duration::from_secs(1)).await;
}
Remember: If it compiles, it's probably correct — but only if you avoid unwrap(), minimize unsafe, and let the type system work for you.
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/affaan-m/rust-patterns/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@affaan-m/rust-patterns@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications. Use when writing or reviewing Rust code and ownership, error handling, traits, or concurrency is in q...
Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You the...
Run aipm add @affaan-m/rust-patterns@1.0.0 in a project that has AIPM initialized.
Supported tools
@affaan-m/rust-patterns@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.