Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.
.claude/skills/loulanyue-rust-patterns/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 240% | 0% |
| case-12 | ✓→✓ | = Same ✓ | 205% | 0% |
| case-02 | ✓→✓ | = Same ✓ | 142% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 125% | 0% |
| case-17 | ✓→✓ | = Same ✓ | 345% | 0% |
Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
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.
Rust's ownership system prevents data races and memory bugs at compile time.
rust// Good: Pass references when you don't need ownership fn process(data: &[u8]) -> usize { data.len() } // Good: Take ownership only when you need to store or consume fn store(data: Vec<u8>) -> Record { Record { payload: data } } // Bad: Cloning unnecessarily to avoid borrow checker fn process_bad(data: &Vec<u8>) -> usize { let cloned = data.clone(); // Wasteful — just borrow cloned.len() }
Cow for Flexible Ownershiprustuse std::borrow::Cow; fn normalize(input: &str) -> Cow<'_, str> { if input.contains(' ') { Cow::Owned(input.replace(' ', "_")) } else { Cow::Borrowed(input) // Zero-cost when no mutation needed } }
Result and ? — Never unwrap() in Productionrust// Good: Propagate errors with context use anyhow::{Context, Result}; fn load_config(path: &str) -> Result<Config> { let content = std::fs::read_to_string(path) .with_context(|| format!("failed to read config from {path}"))?; let config: Config = toml::from_str(&content) .with_context(|| format!("failed to parse config from {path}"))?; Ok(config) } // Bad: Panics on error fn load_config_bad(path: &str) -> Config { let content = std::fs::read_to_string(path).unwrap(); // Panics! toml::from_str(&content).unwrap() }
thiserror, Application Errors with anyhowrust// Library code: structured, typed errors use thiserror::Error; #[derive(Debug, Error)] pub enum StorageError { #[error("record not found: {id}")] NotFound { id: String }, #[error("connection failed")] Connection(#[from] std::io::Error), #[error("invalid data: {0}")] InvalidData(String), } // Application code: flexible error handling use anyhow::{bail, Result}; fn run() -> Result<()> { let config = load_config("app.toml")?; if config.workers == 0 { bail!("worker count must be > 0"); } Ok(()) }
Option Combinators Over Nested Matchingrust// Good: Combinator chain fn find_user_email(users: &[User], id: u64) -> Option<String> { users.iter() .find(|u| u.id == id) .map(|u| u.email.clone()) } // Bad: Deeply nested matching fn find_user_email_bad(users: &[User], id: u64) -> Option<String> { match users.iter().find(|u| u.id == id) { Some(user) => match &user.email { email => Some(email.clone()), }, None => None, } }
rust// Good: Impossible states are unrepresentable enum ConnectionState { Disconnected, Connecting { attempt: u32 }, Connected { session_id: String }, Failed { reason: String, retries: u32 }, } fn handle(state: &ConnectionState) { match state { ConnectionState::Disconnected => connect(), ConnectionState::Connecting { attempt } if *attempt > 3 => abort(), ConnectionState::Connecting { .. } => wait(), ConnectionState::Connected { session_id } => use_session(session_id), ConnectionState::Failed { retries, .. } if *retries < 5 => retry(), ConnectionState::Failed { reason, .. } => log_failure(reason), } }
rust// Good: Handle every variant explicitly match command { Command::Start => start_service(), Command::Stop => stop_service(), Command::Restart => restart_service(), // Adding a new variant forces handling here } // Bad: Wildcard hides new variants match command { Command::Start => start_service(), _ => {} // Silently ignores Stop, Restart, and future variants }
rust// Good: Generic input, concrete output fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> { let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; Ok(buf) } // Good: Trait bounds for multiple constraints fn process<T: Display + Send + 'static>(item: T) -> String { format!("processed: {item}") }
rust// Use when you need heterogeneous collections or plugin systems trait Handler: Send + Sync { fn handle(&self, request: &Request) -> Response; } struct Router { handlers: Vec<Box<dyn Handler>>, } // Use generics when you need performance (monomorphization) fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response { handler.handle(request) }
rust// Good: Distinct types prevent mixing up arguments struct UserId(u64); struct OrderId(u64); fn get_order(user: UserId, order: OrderId) -> Result<Order> { // Can't accidentally swap user and order IDs todo!() } // Bad: Easy to swap arguments fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> { todo!() }
ruststruct ServerConfig { host: String, port: u16, max_connections: usize, } impl ServerConfig { fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder { ServerConfigBuilder { host: host.into(), port, max_connections: 100 } } } struct ServerConfigBuilder { host: String, port: u16, max_connections: usize } impl ServerConfigBuilder { fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self } fn build(self) -> ServerConfig { ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections } } } // Usage: ServerConfig::builder("localhost", 8080).max_connections(200).build()
rust// Good: Declarative, lazy, composable let active_emails: Vec<String> = users.iter() .filter(|u| u.is_active) .map(|u| u.email.clone()) .collect(); // Bad: Imperative accumulation let mut active_emails = Vec::new(); for user in &users { if user.is_active { active_emails.push(user.email.clone()); } }
collect() with Type Annotationrust// Collect into different types let names: Vec<_> = items.iter().map(|i| &i.name).collect(); let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect(); let combined: String = parts.iter().copied().collect(); // Collect Results — short-circuits on first error let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
Arc<Mutex<T>> for Shared Mutable Staterustuse std::sync::{Arc, Mutex}; let counter = Arc::new(Mutex::new(0)); let handles: Vec<_> = (0..10).map(|_| { let counter = Arc::clone(&counter); std::thread::spawn(move || { let mut num = counter.lock().expect("mutex poisoned"); *num += 1; }) }).collect(); for handle in handles { handle.join().expect("worker thread panicked"); }
rustuse std::sync::mpsc; let (tx, rx) = mpsc::sync_channel(16); // Bounded channel with backpressure for i in 0..5 { let tx = tx.clone(); std::thread::spawn(move || { tx.send(format!("message {i}")).expect("receiver disconnected"); }); } drop(tx); // Close sender so rx iterator terminates for msg in rx { println!("{msg}"); }
rustuse tokio::time::Duration; async fn fetch_with_timeout(url: &str) -> Result<String> { let response = tokio::time::timeout( Duration::from_secs(5), reqwest::get(url), ) .await .context("request timed out")? .context("request failed")?; response.text().await.context("failed to read body") } // Spawn concurrent tasks async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> { let handles: Vec<_> = urls.into_iter() .map(|url| tokio::spawn(async move { fetch_with_timeout(&url).await })) .collect(); let mut results = Vec::with_capacity(handles.len()); for handle in handles { results.push(handle.await.unwrap_or_else(|e| panic!("spawned task panicked: {e}"))); } results }
rust// Acceptable: FFI boundary with documented invariants (Rust 2024+) /// # Safety /// `ptr` must be a valid, aligned pointer to an initialized `Widget`. unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget { // SAFETY: caller guarantees ptr is valid and aligned unsafe { &*ptr } } // Acceptable: Performance-critical path with proof of correctness // SAFETY: index is always < len due to the loop bound unsafe { slice.get_unchecked(index) }
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
textmy_app/ ├── src/ │ ├── main.rs │ ├── lib.rs │ ├── auth/ # Domain module │ │ ├── mod.rs │ │ ├── token.rs │ │ └── middleware.rs │ ├── orders/ # Domain module │ │ ├── mod.rs │ │ ├── model.rs │ │ └── service.rs │ └── db/ # Infrastructure │ ├── mod.rs │ └── pool.rs ├── tests/ # Integration tests ├── benches/ # Benchmarks └── Cargo.toml
rust// Good: pub(crate) for internal sharing pub(crate) fn validate_input(input: &str) -> bool { !input.is_empty() } // Good: Re-export public API from lib.rs pub mod auth; pub use auth::AuthMiddleware; // Bad: Making everything pub pub fn internal_helper() {} // Should be pub(crate) or private
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
| 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 |
rust// Bad: .unwrap() in production code let value = map.get("key").unwrap(); // Bad: .clone() to satisfy borrow checker without understanding why let data = expensive_data.clone(); process(&original, &data); // Bad: Using String when &str suffices fn greet(name: String) { /* should be &str */ } // Bad: Box<dyn Error> in libraries (use thiserror instead) fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() } // Bad: Ignoring must_use warnings let _ = validate(input); // Silently discarding a Result // Bad: Blocking in async context async fn bad_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.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-12 | pass→pass | 8,718 | 5,361 | -39% | 1 | 1 | 0% | 1,537 | 4,683 | +205% | 0 | 0 | — |
case-01 | fail→pass | 9,994 | 12,916 | +29% | 1 | 1 | 0% | 1,772 | 6,031 | +240% | 0 | 0 | — |
case-02 | pass→pass | 13,707 | 9,100 | -34% | 1 | 1 | 0% | 2,161 | 5,237 | +142% | 0 | 0 | — |
case-03 | pass→pass | 13,229 | 9,535 | -28% | 1 | 1 | 0% | 2,446 | 5,515 | +125% | 0 | 0 | — |
case-17 | pass→pass | 6,078 | 5,010 | -18% | 1 | 1 | 0% | 1,014 | 4,517 | +345% | 0 | 0 | — |
case-04 | pass→pass | 15,950 | 7,507 | -53% | 1 | 1 | 0% | 2,687 | 5,003 | +86% | 0 | 0 | — |
case-05 | pass→pass | 11,039 | 9,104 | -18% | 1 | 1 | 0% | 2,213 | 5,617 | +154% | 0 | 0 | — |
case-06 | pass→pass | 12,290 | 9,301 | -24% | 1 | 1 | 0% | 2,330 | 5,389 | +131% | 0 | 0 | — |
case-07 | pass→pass | 11,349 | 6,687 | -41% | 1 | 1 | 0% | 1,899 | 4,949 | +161% | 0 | 0 | — |
case-08 | pass→pass | 15,142 | 13,765 | -9% | 1 | 1 | 0% | 2,529 | 6,016 | +138% | 0 | 0 | — |
case-09 | pass→pass | 11,383 | 7,755 | -32% | 1 | 1 | 0% | 1,965 | 5,061 | +158% | 0 | 0 | — |
case-10 | pass→pass | 13,105 | 9,869 | -25% | 1 | 1 | 0% | 2,342 | 5,718 | +144% | 0 | 0 | — |
case-11 | pass→pass | 11,883 | 6,744 | -43% | 1 | 1 | 0% | 2,023 | 4,890 | +142% | 0 | 0 | — |
case-13 | pass→pass | 11,093 | 9,296 | -16% | 1 | 1 | 0% | 1,891 | 5,355 | +183% | 0 | 0 | — |
case-14 | pass→pass | 12,006 | 6,417 | -47% | 1 | 1 | 0% | 2,075 | 4,824 | +132% | 0 | 0 | — |
case-15 | pass→pass | 9,132 | 4,022 | -56% | 1 | 1 | 0% | 1,633 | 4,475 | +174% | 0 | 0 | — |
case-16 | pass→pass | 13,977 | 9,294 | -34% | 1 | 1 | 0% | 2,226 | 5,391 | +142% | 0 | 0 | — |
case-18 | pass→pass | 6,158 | 3,380 | -45% | 1 | 1 | 0% | 1,056 | 4,224 | +300% | 0 | 0 | — |
case-19 | pass→pass | 10,624 | 8,477 | -20% | 1 | 1 | 0% | 1,623 | 5,014 | +209% | 0 | 0 | — |
case-20 | pass→pass | 13,193 | 11,797 | -11% | 1 | 1 | 0% | 2,451 | 5,980 | +144% | 0 | 0 | — |
case-21 | pass→pass | 13,984 | 12,010 | -14% | 1 | 1 | 0% | 2,536 | 6,018 | +137% | 0 | 0 | — |
case-22 | pass→pass | 9,116 | 8,945 | -2% | 1 | 1 | 0% | 1,673 | 5,344 | +219% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +5 percentage points is the difference between those two pass rates over the 22 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.