[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6DAJ0H2Y6ASPKJ5D759NTKA":3,"skill-same:01M6DAJ0H2Y6ASPKJ5D759NTKA":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":27,"linkOnly":28,"markdownContent":29,"markdownBody":30,"frontMatter":31,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":14,"repositoryHtmlUrl":36,"repositoryHomepageUrl":6,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":38,"install":39,"resources":52},"01M6DAJ0H2Y6ASPKJ5D759NTKA","rust-patterns",null,"Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.","Prekzursil\u002Fagent-skills-toolchain","Prekzursil","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F54636077?v=4","01M6DACZ1PCQHD99SCR1YXG28B","Andrei Mihai Visalon","01M6DACZ670WZF535V3WYYSS4Z",0,"MIT","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002F.agents\u002Flibrary\u002Fskills\u002Frust-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26],"rust","rust patterns","patterns","safe","error handling","best practices","concurrency","applications","2026-11-10 10:12:30",false,"---\nname: rust-patterns\ndescription: Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.\norigin: ECC\n---\n\n# Rust Development Patterns\n\nIdiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.\n\n## When to Use\n\n- Writing new Rust code\n- Reviewing Rust code\n- Refactoring existing Rust code\n- Designing crate structure and module layout\n\n## How It Works\n\nThis skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, `Result`\u002F`?` 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\u003CMutex\u003CT>>`, channels, and async\u002Fawait, and minimal `pub` surfaces organized by domain.\n\n## Core Principles\n\n### 1. Ownership and Borrowing\n\nRust's ownership system prevents data races and memory bugs at compile time.\n\n```rust\n\u002F\u002F Good: Pass references when you don't need ownership\nfn process(data: &[u8]) -> usize {\n    data.len()\n}\n\n\u002F\u002F Good: Take ownership only when you need to store or consume\nfn store(data: Vec\u003Cu8>) -> Record {\n    Record { payload: data }\n}\n\n\u002F\u002F Bad: Cloning unnecessarily to avoid borrow checker\nfn process_bad(data: &Vec\u003Cu8>) -> usize {\n    let cloned = data.clone(); \u002F\u002F Wasteful — just borrow\n    cloned.len()\n}\n```\n\n### Use `Cow` for Flexible Ownership\n\n```rust\nuse std::borrow::Cow;\n\nfn normalize(input: &str) -> Cow\u003C'_, str> {\n    if input.contains(' ') {\n        Cow::Owned(input.replace(' ', \"_\"))\n    } else {\n        Cow::Borrowed(input) \u002F\u002F Zero-cost when no mutation needed\n    }\n}\n```\n\n## Error Handling\n\n### Use `Result` and `?` — Never `unwrap()` in Production\n\n```rust\n\u002F\u002F Good: Propagate errors with context\nuse anyhow::{Context, Result};\n\nfn load_config(path: &str) -> Result\u003CConfig> {\n    let content = std::fs::read_to_string(path)\n        .with_context(|| format!(\"failed to read config from {path}\"))?;\n    let config: Config = toml::from_str(&content)\n        .with_context(|| format!(\"failed to parse config from {path}\"))?;\n    Ok(config)\n}\n\n\u002F\u002F Bad: Panics on error\nfn load_config_bad(path: &str) -> Config {\n    let content = std::fs::read_to_string(path).unwrap(); \u002F\u002F Panics!\n    toml::from_str(&content).unwrap()\n}\n```\n\n### Library Errors with `thiserror`, Application Errors with `anyhow`\n\n```rust\n\u002F\u002F Library code: structured, typed errors\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum StorageError {\n    #[error(\"record not found: {id}\")]\n    NotFound { id: String },\n    #[error(\"connection failed\")]\n    Connection(#[from] std::io::Error),\n    #[error(\"invalid data: {0}\")]\n    InvalidData(String),\n}\n\n\u002F\u002F Application code: flexible error handling\nuse anyhow::{bail, Result};\n\nfn run() -> Result\u003C()> {\n    let config = load_config(\"app.toml\")?;\n    if config.workers == 0 {\n        bail!(\"worker count must be > 0\");\n    }\n    Ok(())\n}\n```\n\n### `Option` Combinators Over Nested Matching\n\n```rust\n\u002F\u002F Good: Combinator chain\nfn find_user_email(users: &[User], id: u64) -> Option\u003CString> {\n    users.iter()\n        .find(|u| u.id == id)\n        .map(|u| u.email.clone())\n}\n\n\u002F\u002F Bad: Deeply nested matching\nfn find_user_email_bad(users: &[User], id: u64) -> Option\u003CString> {\n    match users.iter().find(|u| u.id == id) {\n        Some(user) => match &user.email {\n            email => Some(email.clone()),\n        },\n        None => None,\n    }\n}\n```\n\n## Enums and Pattern Matching\n\n### Model States as Enums\n\n```rust\n\u002F\u002F Good: Impossible states are unrepresentable\nenum ConnectionState {\n    Disconnected,\n    Connecting { attempt: u32 },\n    Connected { session_id: String },\n    Failed { reason: String, retries: u32 },\n}\n\nfn handle(state: &ConnectionState) {\n    match state {\n        ConnectionState::Disconnected => connect(),\n        ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),\n        ConnectionState::Connecting { .. } => wait(),\n        ConnectionState::Connected { session_id } => use_session(session_id),\n        ConnectionState::Failed { retries, .. } if *retries \u003C 5 => retry(),\n        ConnectionState::Failed { reason, .. } => log_failure(reason),\n    }\n}\n```\n\n### Exhaustive Matching — No Catch-All for Business Logic\n\n```rust\n\u002F\u002F Good: Handle every variant explicitly\nmatch command {\n    Command::Start => start_service(),\n    Command::Stop => stop_service(),\n    Command::Restart => restart_service(),\n    \u002F\u002F Adding a new variant forces handling here\n}\n\n\u002F\u002F Bad: Wildcard hides new variants\nmatch command {\n    Command::Start => start_service(),\n    _ => {} \u002F\u002F Silently ignores Stop, Restart, and future variants\n}\n```\n\n## Traits and Generics\n\n### Accept Generics, Return Concrete Types\n\n```rust\n\u002F\u002F Good: Generic input, concrete output\nfn read_all(reader: &mut impl Read) -> std::io::Result\u003CVec\u003Cu8>> {\n    let mut buf = Vec::new();\n    reader.read_to_end(&mut buf)?;\n    Ok(buf)\n}\n\n\u002F\u002F Good: Trait bounds for multiple constraints\nfn process\u003CT: Display + Send + 'static>(item: T) -> String {\n    format!(\"processed: {item}\")\n}\n```\n\n### Trait Objects for Dynamic Dispatch\n\n```rust\n\u002F\u002F Use when you need heterogeneous collections or plugin systems\ntrait Handler: Send + Sync {\n    fn handle(&self, request: &Request) -> Response;\n}\n\nstruct Router {\n    handlers: Vec\u003CBox\u003Cdyn Handler>>,\n}\n\n\u002F\u002F Use generics when you need performance (monomorphization)\nfn fast_process\u003CH: Handler>(handler: &H, request: &Request) -> Response {\n    handler.handle(request)\n}\n```\n\n### Newtype Pattern for Type Safety\n\n```rust\n\u002F\u002F Good: Distinct types prevent mixing up arguments\nstruct UserId(u64);\nstruct OrderId(u64);\n\nfn get_order(user: UserId, order: OrderId) -> Result\u003COrder> {\n    \u002F\u002F Can't accidentally swap user and order IDs\n    todo!()\n}\n\n\u002F\u002F Bad: Easy to swap arguments\nfn get_order_bad(user_id: u64, order_id: u64) -> Result\u003COrder> {\n    todo!()\n}\n```\n\n## Structs and Data Modeling\n\n### Builder Pattern for Complex Construction\n\n```rust\nstruct ServerConfig {\n    host: String,\n    port: u16,\n    max_connections: usize,\n}\n\nimpl ServerConfig {\n    fn builder(host: impl Into\u003CString>, port: u16) -> ServerConfigBuilder {\n        ServerConfigBuilder { host: host.into(), port, max_connections: 100 }\n    }\n}\n\nstruct ServerConfigBuilder { host: String, port: u16, max_connections: usize }\n\nimpl ServerConfigBuilder {\n    fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }\n    fn build(self) -> ServerConfig {\n        ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }\n    }\n}\n\n\u002F\u002F Usage: ServerConfig::builder(\"localhost\", 8080).max_connections(200).build()\n```\n\n## Iterators and Closures\n\n### Prefer Iterator Chains Over Manual Loops\n\n```rust\n\u002F\u002F Good: Declarative, lazy, composable\nlet active_emails: Vec\u003CString> = users.iter()\n    .filter(|u| u.is_active)\n    .map(|u| u.email.clone())\n    .collect();\n\n\u002F\u002F Bad: Imperative accumulation\nlet mut active_emails = Vec::new();\nfor user in &users {\n    if user.is_active {\n        active_emails.push(user.email.clone());\n    }\n}\n```\n\n### Use `collect()` with Type Annotation\n\n```rust\n\u002F\u002F Collect into different types\nlet names: Vec\u003C_> = items.iter().map(|i| &i.name).collect();\nlet lookup: HashMap\u003C_, _> = items.iter().map(|i| (i.id, i)).collect();\nlet combined: String = parts.iter().copied().collect();\n\n\u002F\u002F Collect Results — short-circuits on first error\nlet parsed: Result\u003CVec\u003Ci32>, _> = strings.iter().map(|s| s.parse()).collect();\n```\n\n## Concurrency\n\n### `Arc\u003CMutex\u003CT>>` for Shared Mutable State\n\n```rust\nuse std::sync::{Arc, Mutex};\n\nlet counter = Arc::new(Mutex::new(0));\nlet handles: Vec\u003C_> = (0..10).map(|_| {\n    let counter = Arc::clone(&counter);\n    std::thread::spawn(move || {\n        let mut num = counter.lock().expect(\"mutex poisoned\");\n        *num += 1;\n    })\n}).collect();\n\nfor handle in handles {\n    handle.join().expect(\"worker thread panicked\");\n}\n```\n\n### Channels for Message Passing\n\n```rust\nuse std::sync::mpsc;\n\nlet (tx, rx) = mpsc::sync_channel(16); \u002F\u002F Bounded channel with backpressure\n\nfor i in 0..5 {\n    let tx = tx.clone();\n    std::thread::spawn(move || {\n        tx.send(format!(\"message {i}\")).expect(\"receiver disconnected\");\n    });\n}\ndrop(tx); \u002F\u002F Close sender so rx iterator terminates\n\nfor msg in rx {\n    println!(\"{msg}\");\n}\n```\n\n### Async with Tokio\n\n```rust\nuse tokio::time::Duration;\n\nasync fn fetch_with_timeout(url: &str) -> Result\u003CString> {\n    let response = tokio::time::timeout(\n        Duration::from_secs(5),\n        reqwest::get(url),\n    )\n    .await\n    .context(\"request timed out\")?\n    .context(\"request failed\")?;\n\n    response.text().await.context(\"failed to read body\")\n}\n\n\u002F\u002F Spawn concurrent tasks\nasync fn fetch_all(urls: Vec\u003CString>) -> Vec\u003CResult\u003CString>> {\n    let handles: Vec\u003C_> = urls.into_iter()\n        .map(|url| tokio::spawn(async move {\n            fetch_with_timeout(&url).await\n        }))\n        .collect();\n\n    let mut results = Vec::with_capacity(handles.len());\n    for handle in handles {\n        results.push(handle.await.unwrap_or_else(|e| panic!(\"spawned task panicked: {e}\")));\n    }\n    results\n}\n```\n\n## Unsafe Code\n\n### When Unsafe Is Acceptable\n\n```rust\n\u002F\u002F Acceptable: FFI boundary with documented invariants (Rust 2024+)\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F `ptr` must be a valid, aligned pointer to an initialized `Widget`.\nunsafe fn widget_from_raw\u003C'a>(ptr: *const Widget) -> &'a Widget {\n    \u002F\u002F SAFETY: caller guarantees ptr is valid and aligned\n    unsafe { &*ptr }\n}\n\n\u002F\u002F Acceptable: Performance-critical path with proof of correctness\n\u002F\u002F SAFETY: index is always \u003C len due to the loop bound\nunsafe { slice.get_unchecked(index) }\n```\n\n### When Unsafe Is NOT Acceptable\n\n```rust\n\u002F\u002F Bad: Using unsafe to bypass borrow checker\n\u002F\u002F Bad: Using unsafe for convenience\n\u002F\u002F Bad: Using unsafe without a Safety comment\n\u002F\u002F Bad: Transmuting between unrelated types\n```\n\n## Module System and Crate Structure\n\n### Organize by Domain, Not by Type\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # Domain module\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # Domain module\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # Infrastructure\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # Integration tests\n├── benches\u002F           # Benchmarks\n└── Cargo.toml\n```\n\n### Visibility — Expose Minimally\n\n```rust\n\u002F\u002F Good: pub(crate) for internal sharing\npub(crate) fn validate_input(input: &str) -> bool {\n    !input.is_empty()\n}\n\n\u002F\u002F Good: Re-export public API from lib.rs\npub mod auth;\npub use auth::AuthMiddleware;\n\n\u002F\u002F Bad: Making everything pub\npub fn internal_helper() {} \u002F\u002F Should be pub(crate) or private\n```\n\n## Tooling Integration\n\n### Essential Commands\n\n```bash\n# Build and check\ncargo build\ncargo check              # Fast type checking without codegen\ncargo clippy             # Lints and suggestions\ncargo fmt                # Format code\n\n# Testing\ncargo test\ncargo test -- --nocapture    # Show println output\ncargo test --lib             # Unit tests only\ncargo test --test integration # Integration tests only\n\n# Dependencies\ncargo audit              # Security audit\ncargo tree               # Dependency tree\ncargo update             # Update dependencies\n\n# Performance\ncargo bench              # Run benchmarks\n```\n\n## Quick Reference: Rust Idioms\n\n| Idiom | Description |\n|-------|-------------|\n| Borrow, don't clone | Pass `&T` instead of cloning unless ownership is needed |\n| Make illegal states unrepresentable | Use enums to model valid states only |\n| `?` over `unwrap()` | Propagate errors, never panic in library\u002Fproduction code |\n| Parse, don't validate | Convert unstructured data to typed structs at the boundary |\n| Newtype for type safety | Wrap primitives in newtypes to prevent argument swaps |\n| Prefer iterators over loops | Declarative chains are clearer and often faster |\n| `#[must_use]` on Results | Ensure callers handle return values |\n| `Cow` for flexible ownership | Avoid allocations when borrowing suffices |\n| Exhaustive matching | No wildcard `_` for business-critical enums |\n| Minimal `pub` surface | Use `pub(crate)` for internal APIs |\n\n## Anti-Patterns to Avoid\n\n```rust\n\u002F\u002F Bad: .unwrap() in production code\nlet value = map.get(\"key\").unwrap();\n\n\u002F\u002F Bad: .clone() to satisfy borrow checker without understanding why\nlet data = expensive_data.clone();\nprocess(&original, &data);\n\n\u002F\u002F Bad: Using String when &str suffices\nfn greet(name: String) { \u002F* should be &str *\u002F }\n\n\u002F\u002F Bad: Box\u003Cdyn Error> in libraries (use thiserror instead)\nfn parse(input: &str) -> Result\u003CData, Box\u003Cdyn std::error::Error>> { todo!() }\n\n\u002F\u002F Bad: Ignoring must_use warnings\nlet _ = validate(input); \u002F\u002F Silently discarding a Result\n\n\u002F\u002F Bad: Blocking in async context\nasync fn bad_async() {\n    std::thread::sleep(Duration::from_secs(1)); \u002F\u002F Blocks the executor!\n    \u002F\u002F Use: tokio::time::sleep(Duration::from_secs(1)).await;\n}\n```\n\n**Remember**: If it compiles, it's probably correct — but only if you avoid `unwrap()`, minimize `unsafe`, and let the type system work for you.\n","# Rust Development Patterns\n\nIdiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.\n\n## When to Use\n\n- Writing new Rust code\n- Reviewing Rust code\n- Refactoring existing Rust code\n- Designing crate structure and module layout\n\n## How It Works\n\nThis skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, `Result`\u002F`?` 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\u003CMutex\u003CT>>`, channels, and async\u002Fawait, and minimal `pub` surfaces organized by domain.\n\n## Core Principles\n\n### 1. Ownership and Borrowing\n\nRust's ownership system prevents data races and memory bugs at compile time.\n\n```rust\n\u002F\u002F Good: Pass references when you don't need ownership\nfn process(data: &[u8]) -> usize {\n    data.len()\n}\n\n\u002F\u002F Good: Take ownership only when you need to store or consume\nfn store(data: Vec\u003Cu8>) -> Record {\n    Record { payload: data }\n}\n\n\u002F\u002F Bad: Cloning unnecessarily to avoid borrow checker\nfn process_bad(data: &Vec\u003Cu8>) -> usize {\n    let cloned = data.clone(); \u002F\u002F Wasteful — just borrow\n    cloned.len()\n}\n```\n\n### Use `Cow` for Flexible Ownership\n\n```rust\nuse std::borrow::Cow;\n\nfn normalize(input: &str) -> Cow\u003C'_, str> {\n    if input.contains(' ') {\n        Cow::Owned(input.replace(' ', \"_\"))\n    } else {\n        Cow::Borrowed(input) \u002F\u002F Zero-cost when no mutation needed\n    }\n}\n```\n\n## Error Handling\n\n### Use `Result` and `?` — Never `unwrap()` in Production\n\n```rust\n\u002F\u002F Good: Propagate errors with context\nuse anyhow::{Context, Result};\n\nfn load_config(path: &str) -> Result\u003CConfig> {\n    let content = std::fs::read_to_string(path)\n        .with_context(|| format!(\"failed to read config from {path}\"))?;\n    let config: Config = toml::from_str(&content)\n        .with_context(|| format!(\"failed to parse config from {path}\"))?;\n    Ok(config)\n}\n\n\u002F\u002F Bad: Panics on error\nfn load_config_bad(path: &str) -> Config {\n    let content = std::fs::read_to_string(path).unwrap(); \u002F\u002F Panics!\n    toml::from_str(&content).unwrap()\n}\n```\n\n### Library Errors with `thiserror`, Application Errors with `anyhow`\n\n```rust\n\u002F\u002F Library code: structured, typed errors\nuse thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum StorageError {\n    #[error(\"record not found: {id}\")]\n    NotFound { id: String },\n    #[error(\"connection failed\")]\n    Connection(#[from] std::io::Error),\n    #[error(\"invalid data: {0}\")]\n    InvalidData(String),\n}\n\n\u002F\u002F Application code: flexible error handling\nuse anyhow::{bail, Result};\n\nfn run() -> Result\u003C()> {\n    let config = load_config(\"app.toml\")?;\n    if config.workers == 0 {\n        bail!(\"worker count must be > 0\");\n    }\n    Ok(())\n}\n```\n\n### `Option` Combinators Over Nested Matching\n\n```rust\n\u002F\u002F Good: Combinator chain\nfn find_user_email(users: &[User], id: u64) -> Option\u003CString> {\n    users.iter()\n        .find(|u| u.id == id)\n        .map(|u| u.email.clone())\n}\n\n\u002F\u002F Bad: Deeply nested matching\nfn find_user_email_bad(users: &[User], id: u64) -> Option\u003CString> {\n    match users.iter().find(|u| u.id == id) {\n        Some(user) => match &user.email {\n            email => Some(email.clone()),\n        },\n        None => None,\n    }\n}\n```\n\n## Enums and Pattern Matching\n\n### Model States as Enums\n\n```rust\n\u002F\u002F Good: Impossible states are unrepresentable\nenum ConnectionState {\n    Disconnected,\n    Connecting { attempt: u32 },\n    Connected { session_id: String },\n    Failed { reason: String, retries: u32 },\n}\n\nfn handle(state: &ConnectionState) {\n    match state {\n        ConnectionState::Disconnected => connect(),\n        ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),\n        ConnectionState::Connecting { .. } => wait(),\n        ConnectionState::Connected { session_id } => use_session(session_id),\n        ConnectionState::Failed { retries, .. } if *retries \u003C 5 => retry(),\n        ConnectionState::Failed { reason, .. } => log_failure(reason),\n    }\n}\n```\n\n### Exhaustive Matching — No Catch-All for Business Logic\n\n```rust\n\u002F\u002F Good: Handle every variant explicitly\nmatch command {\n    Command::Start => start_service(),\n    Command::Stop => stop_service(),\n    Command::Restart => restart_service(),\n    \u002F\u002F Adding a new variant forces handling here\n}\n\n\u002F\u002F Bad: Wildcard hides new variants\nmatch command {\n    Command::Start => start_service(),\n    _ => {} \u002F\u002F Silently ignores Stop, Restart, and future variants\n}\n```\n\n## Traits and Generics\n\n### Accept Generics, Return Concrete Types\n\n```rust\n\u002F\u002F Good: Generic input, concrete output\nfn read_all(reader: &mut impl Read) -> std::io::Result\u003CVec\u003Cu8>> {\n    let mut buf = Vec::new();\n    reader.read_to_end(&mut buf)?;\n    Ok(buf)\n}\n\n\u002F\u002F Good: Trait bounds for multiple constraints\nfn process\u003CT: Display + Send + 'static>(item: T) -> String {\n    format!(\"processed: {item}\")\n}\n```\n\n### Trait Objects for Dynamic Dispatch\n\n```rust\n\u002F\u002F Use when you need heterogeneous collections or plugin systems\ntrait Handler: Send + Sync {\n    fn handle(&self, request: &Request) -> Response;\n}\n\nstruct Router {\n    handlers: Vec\u003CBox\u003Cdyn Handler>>,\n}\n\n\u002F\u002F Use generics when you need performance (monomorphization)\nfn fast_process\u003CH: Handler>(handler: &H, request: &Request) -> Response {\n    handler.handle(request)\n}\n```\n\n### Newtype Pattern for Type Safety\n\n```rust\n\u002F\u002F Good: Distinct types prevent mixing up arguments\nstruct UserId(u64);\nstruct OrderId(u64);\n\nfn get_order(user: UserId, order: OrderId) -> Result\u003COrder> {\n    \u002F\u002F Can't accidentally swap user and order IDs\n    todo!()\n}\n\n\u002F\u002F Bad: Easy to swap arguments\nfn get_order_bad(user_id: u64, order_id: u64) -> Result\u003COrder> {\n    todo!()\n}\n```\n\n## Structs and Data Modeling\n\n### Builder Pattern for Complex Construction\n\n```rust\nstruct ServerConfig {\n    host: String,\n    port: u16,\n    max_connections: usize,\n}\n\nimpl ServerConfig {\n    fn builder(host: impl Into\u003CString>, port: u16) -> ServerConfigBuilder {\n        ServerConfigBuilder { host: host.into(), port, max_connections: 100 }\n    }\n}\n\nstruct ServerConfigBuilder { host: String, port: u16, max_connections: usize }\n\nimpl ServerConfigBuilder {\n    fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }\n    fn build(self) -> ServerConfig {\n        ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }\n    }\n}\n\n\u002F\u002F Usage: ServerConfig::builder(\"localhost\", 8080).max_connections(200).build()\n```\n\n## Iterators and Closures\n\n### Prefer Iterator Chains Over Manual Loops\n\n```rust\n\u002F\u002F Good: Declarative, lazy, composable\nlet active_emails: Vec\u003CString> = users.iter()\n    .filter(|u| u.is_active)\n    .map(|u| u.email.clone())\n    .collect();\n\n\u002F\u002F Bad: Imperative accumulation\nlet mut active_emails = Vec::new();\nfor user in &users {\n    if user.is_active {\n        active_emails.push(user.email.clone());\n    }\n}\n```\n\n### Use `collect()` with Type Annotation\n\n```rust\n\u002F\u002F Collect into different types\nlet names: Vec\u003C_> = items.iter().map(|i| &i.name).collect();\nlet lookup: HashMap\u003C_, _> = items.iter().map(|i| (i.id, i)).collect();\nlet combined: String = parts.iter().copied().collect();\n\n\u002F\u002F Collect Results — short-circuits on first error\nlet parsed: Result\u003CVec\u003Ci32>, _> = strings.iter().map(|s| s.parse()).collect();\n```\n\n## Concurrency\n\n### `Arc\u003CMutex\u003CT>>` for Shared Mutable State\n\n```rust\nuse std::sync::{Arc, Mutex};\n\nlet counter = Arc::new(Mutex::new(0));\nlet handles: Vec\u003C_> = (0..10).map(|_| {\n    let counter = Arc::clone(&counter);\n    std::thread::spawn(move || {\n        let mut num = counter.lock().expect(\"mutex poisoned\");\n        *num += 1;\n    })\n}).collect();\n\nfor handle in handles {\n    handle.join().expect(\"worker thread panicked\");\n}\n```\n\n### Channels for Message Passing\n\n```rust\nuse std::sync::mpsc;\n\nlet (tx, rx) = mpsc::sync_channel(16); \u002F\u002F Bounded channel with backpressure\n\nfor i in 0..5 {\n    let tx = tx.clone();\n    std::thread::spawn(move || {\n        tx.send(format!(\"message {i}\")).expect(\"receiver disconnected\");\n    });\n}\ndrop(tx); \u002F\u002F Close sender so rx iterator terminates\n\nfor msg in rx {\n    println!(\"{msg}\");\n}\n```\n\n### Async with Tokio\n\n```rust\nuse tokio::time::Duration;\n\nasync fn fetch_with_timeout(url: &str) -> Result\u003CString> {\n    let response = tokio::time::timeout(\n        Duration::from_secs(5),\n        reqwest::get(url),\n    )\n    .await\n    .context(\"request timed out\")?\n    .context(\"request failed\")?;\n\n    response.text().await.context(\"failed to read body\")\n}\n\n\u002F\u002F Spawn concurrent tasks\nasync fn fetch_all(urls: Vec\u003CString>) -> Vec\u003CResult\u003CString>> {\n    let handles: Vec\u003C_> = urls.into_iter()\n        .map(|url| tokio::spawn(async move {\n            fetch_with_timeout(&url).await\n        }))\n        .collect();\n\n    let mut results = Vec::with_capacity(handles.len());\n    for handle in handles {\n        results.push(handle.await.unwrap_or_else(|e| panic!(\"spawned task panicked: {e}\")));\n    }\n    results\n}\n```\n\n## Unsafe Code\n\n### When Unsafe Is Acceptable\n\n```rust\n\u002F\u002F Acceptable: FFI boundary with documented invariants (Rust 2024+)\n\u002F\u002F\u002F # Safety\n\u002F\u002F\u002F `ptr` must be a valid, aligned pointer to an initialized `Widget`.\nunsafe fn widget_from_raw\u003C'a>(ptr: *const Widget) -> &'a Widget {\n    \u002F\u002F SAFETY: caller guarantees ptr is valid and aligned\n    unsafe { &*ptr }\n}\n\n\u002F\u002F Acceptable: Performance-critical path with proof of correctness\n\u002F\u002F SAFETY: index is always \u003C len due to the loop bound\nunsafe { slice.get_unchecked(index) }\n```\n\n### When Unsafe Is NOT Acceptable\n\n```rust\n\u002F\u002F Bad: Using unsafe to bypass borrow checker\n\u002F\u002F Bad: Using unsafe for convenience\n\u002F\u002F Bad: Using unsafe without a Safety comment\n\u002F\u002F Bad: Transmuting between unrelated types\n```\n\n## Module System and Crate Structure\n\n### Organize by Domain, Not by Type\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # Domain module\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # Domain module\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # Infrastructure\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # Integration tests\n├── benches\u002F           # Benchmarks\n└── Cargo.toml\n```\n\n### Visibility — Expose Minimally\n\n```rust\n\u002F\u002F Good: pub(crate) for internal sharing\npub(crate) fn validate_input(input: &str) -> bool {\n    !input.is_empty()\n}\n\n\u002F\u002F Good: Re-export public API from lib.rs\npub mod auth;\npub use auth::AuthMiddleware;\n\n\u002F\u002F Bad: Making everything pub\npub fn internal_helper() {} \u002F\u002F Should be pub(crate) or private\n```\n\n## Tooling Integration\n\n### Essential Commands\n\n```bash\n# Build and check\ncargo build\ncargo check              # Fast type checking without codegen\ncargo clippy             # Lints and suggestions\ncargo fmt                # Format code\n\n# Testing\ncargo test\ncargo test -- --nocapture    # Show println output\ncargo test --lib             # Unit tests only\ncargo test --test integration # Integration tests only\n\n# Dependencies\ncargo audit              # Security audit\ncargo tree               # Dependency tree\ncargo update             # Update dependencies\n\n# Performance\ncargo bench              # Run benchmarks\n```\n\n## Quick Reference: Rust Idioms\n\n| Idiom | Description |\n|-------|-------------|\n| Borrow, don't clone | Pass `&T` instead of cloning unless ownership is needed |\n| Make illegal states unrepresentable | Use enums to model valid states only |\n| `?` over `unwrap()` | Propagate errors, never panic in library\u002Fproduction code |\n| Parse, don't validate | Convert unstructured data to typed structs at the boundary |\n| Newtype for type safety | Wrap primitives in newtypes to prevent argument swaps |\n| Prefer iterators over loops | Declarative chains are clearer and often faster |\n| `#[must_use]` on Results | Ensure callers handle return values |\n| `Cow` for flexible ownership | Avoid allocations when borrowing suffices |\n| Exhaustive matching | No wildcard `_` for business-critical enums |\n| Minimal `pub` surface | Use `pub(crate)` for internal APIs |\n\n## Anti-Patterns to Avoid\n\n```rust\n\u002F\u002F Bad: .unwrap() in production code\nlet value = map.get(\"key\").unwrap();\n\n\u002F\u002F Bad: .clone() to satisfy borrow checker without understanding why\nlet data = expensive_data.clone();\nprocess(&original, &data);\n\n\u002F\u002F Bad: Using String when &str suffices\nfn greet(name: String) { \u002F* should be &str *\u002F }\n\n\u002F\u002F Bad: Box\u003Cdyn Error> in libraries (use thiserror instead)\nfn parse(input: &str) -> Result\u003CData, Box\u003Cdyn std::error::Error>> { todo!() }\n\n\u002F\u002F Bad: Ignoring must_use warnings\nlet _ = validate(input); \u002F\u002F Silently discarding a Result\n\n\u002F\u002F Bad: Blocking in async context\nasync fn bad_async() {\n    std::thread::sleep(Duration::from_secs(1)); \u002F\u002F Blocks the executor!\n    \u002F\u002F Use: tokio::time::sleep(Duration::from_secs(1)).await;\n}\n```\n\n**Remember**: If it compiles, it's probably correct — but only if you avoid `unwrap()`, minimize `unsafe`, and let the type system work for you.\n",{"name":5,"origin":32,"description":7},"ECC","main","a298c929b6cbd662e1fce54302ce520d5ceea1a5",".agents\u002Flibrary\u002Fskills\u002Frust-patterns","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain","https:\u002F\u002Fgithub.com\u002FPrekzursil","2026-11-02 14:30:57",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add Prekzursil\u002Fagent-skills-toolchain --skill rust-patterns",{"tool":45,"command":46},"bunx","bunx skills add Prekzursil\u002Fagent-skills-toolchain --skill rust-patterns",{"tool":48,"command":49},"pnpm","pnpm dlx skills add Prekzursil\u002Fagent-skills-toolchain --skill rust-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002F.agents\u002Flibrary\u002Fskills\u002Frust-patterns\u002FSKILL.md",true,[53,59,63,67],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"scripts\u002Fcreate_tutorial.py","SCRIPT","脚本",6392,"https:\u002F\u002Fgithub.com\u002Fxiaoyuge886\u002Fharness_assistance\u002Fblob\u002Frefactor\u002Funified-packaging\u002Fapps\u002Fagent-mesh\u002Fdata\u002Fplugins\u002Fgithub\u002FEveryInc-compound-engineering-plugin\u002Fplugins\u002Fcoding-tutor\u002Fskills\u002Fcoding-tutor\u002Fscripts\u002Fcreate_tutorial.py",{"path":60,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":61,"sourceHtmlUrl":62},"scripts\u002Findex_tutorials.py",6398,"https:\u002F\u002Fgithub.com\u002Fxiaoyuge886\u002Fharness_assistance\u002Fblob\u002Frefactor\u002Funified-packaging\u002Fapps\u002Fagent-mesh\u002Fdata\u002Fplugins\u002Fgithub\u002FEveryInc-compound-engineering-plugin\u002Fplugins\u002Fcoding-tutor\u002Fskills\u002Fcoding-tutor\u002Fscripts\u002Findex_tutorials.py",{"path":64,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":65,"sourceHtmlUrl":66},"scripts\u002Fquiz_priority.py",5536,"https:\u002F\u002Fgithub.com\u002Fxiaoyuge886\u002Fharness_assistance\u002Fblob\u002Frefactor\u002Funified-packaging\u002Fapps\u002Fagent-mesh\u002Fdata\u002Fplugins\u002Fgithub\u002FEveryInc-compound-engineering-plugin\u002Fplugins\u002Fcoding-tutor\u002Fskills\u002Fcoding-tutor\u002Fscripts\u002Fquiz_priority.py",{"path":68,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":69,"sourceHtmlUrl":70},"scripts\u002Fsetup_tutorials.py",3660,"https:\u002F\u002Fgithub.com\u002Fxiaoyuge886\u002Fharness_assistance\u002Fblob\u002Frefactor\u002Funified-packaging\u002Fapps\u002Fagent-mesh\u002Fdata\u002Fplugins\u002Fgithub\u002FEveryInc-compound-engineering-plugin\u002Fplugins\u002Fcoding-tutor\u002Fskills\u002Fcoding-tutor\u002Fscripts\u002Fsetup_tutorials.py",[72,94,125,152,166,182],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":27},"01M6DF7D7478R55P46REYH4QAC","clarify-requirements","Resolve genuine pre-execution ambiguity by scanning repo context, generating 1-6 grounded options, and asking 1-3 focused questions via AskUserQuestion. NOT for mid-task use (injection risk); NOT when the goal is already unambiguous; use to disambiguate vague prompts before any file edits.","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Fworkspace-hooks\u002Fskills\u002Fclarify-requirements\u002FSKILL.md",[],[79,80,81,82,83,84,85,86,87,88,89,90,91,92,93],"clarify requirements","clarify","requirements","risk","options","task","prompts","goal","scanning","use","context","repo","injection","execution","file",{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":105,"publishedAt":27},"01M6DF79CA4BHJS66J8EZDBPWJ","openmm-md","Run FREE, open-source, Windows-native GPU molecular dynamics via the openmm-md MCP (OpenMM + CUDA on the local NVIDIA GPU). Use for protein \u002F protein-ligand MD when you want a free stack or are on Windows without a Schrodinger license. Covers the full workflow (prepare, solvate, minimize, equilibrate, production, analyze, mmgbsa) AND an honest decision guide vs Schrodinger Desmond, including how to run Desmond legitimately on Linux or a cloud GPU with a real license. This is a deliberately LESSER free alternative and does NOT replace the schrodinger MCP tools. Do NOT use it to pick a free tool when a validated FEP+, WaterMap, IFD-MD, or Prime MM-GBSA result is actually required.","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Fmcp\u002Fopenmm-md-mcp\u002Fskill\u002Fopenmm-md\u002FSKILL.md",[100],{"categoryNo":101,"categoryName":102,"taxonomyType":103,"taxonomyTypeDesc":104},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[106,107,108,109,110,111,112,113,114,115,116,117,118,119,88,120,121,122,123,124],"openmm md","how","decision","pick","linux","analyze","tool","stack","open","NVIDIA","gpu","license","workflow","windows","free","molecular dynamics","local","do","MCP",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":137,"publishedAt":27},"01M6DF76C1MG85VEWP8VZCBNMN","visual-review","Take screenshots of web pages and UI using Playwright for visual review and iteration","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Feditor\u002Fmetaswarm\u002Fskills\u002Fvisual-review\u002FSKILL.md",[131,134],{"categoryNo":132,"categoryName":133,"taxonomyType":103,"taxonomyTypeDesc":104},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":135,"categoryName":136,"taxonomyType":103,"taxonomyTypeDesc":104},"01JBSEEDCAT000000000000008","测试与质量",[138,139,140,141,142,143,144,145,146,147,107,148,149,150,151],"review","visual","visual review","pages","web","false","iteration","take","check","slides","ui","screenshot","playwright","screenshots",{"skillNo":153,"name":154,"nameZh":6,"description":155,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":27},"01M6DF73AQVCBZKEN0YXEX9FXP","status","Diagnostic status report — shows metaswarm installation state, project setup, and potential issues","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Feditor\u002Fmetaswarm\u002Fskills\u002Fstatus\u002FSKILL.md",[],[154,159,160,161,162,163,164,165],"setup","report","project","installation","project setup","issues","state",{"skillNo":167,"name":168,"nameZh":6,"description":169,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":170,"categories":171,"keywords":173,"publishedAt":27},"01M6DF6X6C2XB0P6GX76P7TTYV","start","Use when starting work on any task, when the user mentions metaswarm, or when the user wants to begin tracked development work","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Feditor\u002Fmetaswarm\u002Fskills\u002Fstart\u002FSKILL.md",[172],{"categoryNo":101,"categoryName":102,"taxonomyType":103,"taxonomyTypeDesc":104},[168,174,84,175,176,177,88,178,179,180,181],"start issue","issue","ready","work on issue","user","work","work on","development",{"skillNo":183,"name":159,"nameZh":6,"description":184,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":187,"publishedAt":27},"01M6DF6QMJ9AJKFKHHKRT005PQ","Interactive project setup — detects your project, configures metaswarm, writes project-local files","https:\u002F\u002Fgithub.com\u002FPrekzursil\u002Fagent-skills-toolchain\u002Fblob\u002Fmain\u002Ftools\u002Feditor\u002Fmetaswarm\u002Fskills\u002Fsetup\u002FSKILL.md",[],[159,161,122,188,163,189],"files","interactive"]