[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AKFGF51EX4Z3Y020Y7DVPX":3,"skill-same:01M7AKFGF51EX4Z3Y020Y7DVPX":48},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AKFGF51EX4Z3Y020Y7DVPX","rust-patterns",null,"慣用的なRustパターン、所有権、エラー処理、トレイト、並行処理、および安全で高性能なアプリケーションを構築するためのベストプラクティス。","Cyrilthetecchieee\u002Fcyril-code-","Cyrilthetecchieee","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219787998?v=4","01M7AF0MMMKRAA0H61XMJPV92H","Julian Cyril D ","01M7AF0MQ10AVG6QJQ1C2BC0F5",2,"MIT","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Frust-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: rust-patterns\ndescription: 慣用的なRustパターン、所有権、エラー処理、トレイト、並行処理、および安全で高性能なアプリケーションを構築するためのベストプラクティス。\norigin: ECC\n---\n\n# Rust 開発パターン\n\n安全で高性能かつ保守性の高いアプリケーションを構築するための慣用的なRustパターンとベストプラクティス。\n\n## 使用場面\n\n* 新しいRustコードを書く場合\n* Rustコードをレビューする場合\n* 既存のRustコードをリファクタリングする場合\n* クレート構造とモジュールレイアウトを設計する場合\n\n## 動作原理\n\nこのスキルは6つの重要な領域で慣用的なRustの規約を強制する：コンパイル時のデータ競合防止のための所有権と借用、ライブラリでは`thiserror`、アプリケーションでは`anyhow`を使用した`Result`\u002F`?`エラー伝播、不正な状態を表現不可能にする列挙型と完全パターンマッチング、ゼロコスト抽象化のためのトレイトとジェネリクス、`Arc\u003CMutex\u003CT>>`、チャンネル、async\u002Fawaitによる安全な並行処理、ドメインで整理された最小化された`pub`インターフェース。\n\n## コア原則\n\n### 1. 所有権と借用\n\nRustの所有権システムはコンパイル時にデータ競合とメモリエラーを防ぐ。\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### 柔軟な所有権のための `Cow` の使用\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## エラー処理\n\n### `Result` と `?` を使用する——本番環境では `unwrap()` を絶対に使わない\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### ライブラリエラーには `thiserror`、アプリケーションエラーには `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` コンビネーターを優先する\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## 列挙型とパターンマッチング\n\n### 状態を列挙型としてモデル化する\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### 完全マッチング——ビジネスロジックではワイルドカードを使わない\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## トレイトとジェネリクス\n\n### ジェネリックを受け取り、具体的な型を返す\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### 動的ディスパッチにトレイトオブジェクトを使用する\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パターンを使用する\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## 構造体とデータモデリング\n\n### 複雑な構築にはビルダーパターンを使用する\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## イテレーターとクロージャー\n\n### 手動ループの代わりにイテレーターチェーンを優先する\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### 型注釈付きの `collect()` を使用する\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## 並行処理\n\n### 共有可変状態には `Arc\u003CMutex\u003CT>>` を使用する\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### メッセージパッシングにチャンネルを使用する\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### 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## アンセーフコード\n\n### Unsafe を使用できる場合\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### Unsafe を使用してはいけない場合\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## モジュールシステムとクレート構造\n\n### 型ではなくドメインで整理する\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # ドメインモジュール\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # ドメインモジュール\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # インフラストラクチャ\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # 統合テスト\n├── benches\u002F           # ベンチマーク\n└── Cargo.toml\n```\n\n### 可視性——露出を最小化する\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## ツール統合\n\n### 基本コマンド\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## クイックリファレンス：Rustのイディオム\n\n| イディオム | 説明 |\n|-------|-------------|\n| 借用、クローンではなく | 所有権が必要でなければ `&T` を渡し、クローンしない |\n| 不正な状態を表現不可能にする | 列挙型を使用して有効な状態のみをモデル化する |\n| `unwrap()` より `?` | エラーを伝播し、ライブラリ\u002F本番コードでパニックしない |\n| 検証より解析 | 境界で非構造化データを型付き構造体に変換する |\n| 型安全のためのNewtype | 基本型をnewtypeでラップして引数の取り違えを防ぐ |\n| ループよりイテレーターを優先 | 宣言的なチェーンはより明確で通常より高速 |\n| Resultに `#[must_use]` を使用 | 呼び出し元が戻り値を処理することを保証する |\n| 柔軟な所有権のために `Cow` を使用 | 借用で十分な場合にアロケーションを避ける |\n| 完全マッチング | ビジネスクリティカルな列挙型でワイルドカード `_` を使わない |\n| `pub` インターフェースを最小化 | 内部APIには `pub(crate)` を使用 |\n\n## 避けるべきアンチパターン\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**覚えておくこと**：コンパイルが通れば、おそらく正しい——ただし `unwrap()` を避け、`unsafe` を最小化し、型システムを活用することが前提。\n","# Rust 開発パターン\n\n安全で高性能かつ保守性の高いアプリケーションを構築するための慣用的なRustパターンとベストプラクティス。\n\n## 使用場面\n\n* 新しいRustコードを書く場合\n* Rustコードをレビューする場合\n* 既存のRustコードをリファクタリングする場合\n* クレート構造とモジュールレイアウトを設計する場合\n\n## 動作原理\n\nこのスキルは6つの重要な領域で慣用的なRustの規約を強制する：コンパイル時のデータ競合防止のための所有権と借用、ライブラリでは`thiserror`、アプリケーションでは`anyhow`を使用した`Result`\u002F`?`エラー伝播、不正な状態を表現不可能にする列挙型と完全パターンマッチング、ゼロコスト抽象化のためのトレイトとジェネリクス、`Arc\u003CMutex\u003CT>>`、チャンネル、async\u002Fawaitによる安全な並行処理、ドメインで整理された最小化された`pub`インターフェース。\n\n## コア原則\n\n### 1. 所有権と借用\n\nRustの所有権システムはコンパイル時にデータ競合とメモリエラーを防ぐ。\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### 柔軟な所有権のための `Cow` の使用\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## エラー処理\n\n### `Result` と `?` を使用する——本番環境では `unwrap()` を絶対に使わない\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### ライブラリエラーには `thiserror`、アプリケーションエラーには `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` コンビネーターを優先する\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## 列挙型とパターンマッチング\n\n### 状態を列挙型としてモデル化する\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### 完全マッチング——ビジネスロジックではワイルドカードを使わない\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## トレイトとジェネリクス\n\n### ジェネリックを受け取り、具体的な型を返す\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### 動的ディスパッチにトレイトオブジェクトを使用する\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パターンを使用する\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## 構造体とデータモデリング\n\n### 複雑な構築にはビルダーパターンを使用する\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## イテレーターとクロージャー\n\n### 手動ループの代わりにイテレーターチェーンを優先する\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### 型注釈付きの `collect()` を使用する\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## 並行処理\n\n### 共有可変状態には `Arc\u003CMutex\u003CT>>` を使用する\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### メッセージパッシングにチャンネルを使用する\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### 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## アンセーフコード\n\n### Unsafe を使用できる場合\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### Unsafe を使用してはいけない場合\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## モジュールシステムとクレート構造\n\n### 型ではなくドメインで整理する\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # ドメインモジュール\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # ドメインモジュール\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # インフラストラクチャ\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # 統合テスト\n├── benches\u002F           # ベンチマーク\n└── Cargo.toml\n```\n\n### 可視性——露出を最小化する\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## ツール統合\n\n### 基本コマンド\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## クイックリファレンス：Rustのイディオム\n\n| イディオム | 説明 |\n|-------|-------------|\n| 借用、クローンではなく | 所有権が必要でなければ `&T` を渡し、クローンしない |\n| 不正な状態を表現不可能にする | 列挙型を使用して有効な状態のみをモデル化する |\n| `unwrap()` より `?` | エラーを伝播し、ライブラリ\u002F本番コードでパニックしない |\n| 検証より解析 | 境界で非構造化データを型付き構造体に変換する |\n| 型安全のためのNewtype | 基本型をnewtypeでラップして引数の取り違えを防ぐ |\n| ループよりイテレーターを優先 | 宣言的なチェーンはより明確で通常より高速 |\n| Resultに `#[must_use]` を使用 | 呼び出し元が戻り値を処理することを保証する |\n| 柔軟な所有権のために `Cow` を使用 | 借用で十分な場合にアロケーションを避ける |\n| 完全マッチング | ビジネスクリティカルな列挙型でワイルドカード `_` を使わない |\n| `pub` インターフェースを最小化 | 内部APIには `pub(crate)` を使用 |\n\n## 避けるべきアンチパターン\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**覚えておくこと**：コンパイルが通れば、おそらく正しい——ただし `unwrap()` を避け、`unsafe` を最小化し、型システムを活用することが前提。\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Frust-patterns",0,"https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee","https:\u002F\u002Fwithcyril.me\u002F","Hi, I’m Julian Cyril D, a Computer Science and Business Systems student at PSNACET.\r\nI’m passionate about full-stack development, UI\u002FUX design, and building sma","2026-11-04 23:28:50",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Cyrilthetecchieee\u002Fcyril-code- --skill rust-patterns",{"tool":40,"command":41},"bunx","bunx skills add Cyrilthetecchieee\u002Fcyril-code- --skill rust-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Cyrilthetecchieee\u002Fcyril-code- --skill rust-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Frust-patterns\u002FSKILL.md",true,[],[49,58,65,73,80,87],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":54,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7AQV6CYX8RMC78420V9WZ62","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AQV2895N3S1MEX6K76G6G2","youtube-downloader","Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fvideo-downloader\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AQTRNX62DNKVZ5GXEHRBKB","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AQTNNVHAAN9H6DA8T6ZVE0","template-skill","Replace with description of the skill and when Claude should use it.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftemplate-skill\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AQTJ3MQ6AKX152MEX2MYCC","tailored-resume-generator","Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftailored-resume-generator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7AQTD7D5MYET2YWG7HG9WM3","slack-gif-creator","Toolkit for creating animated GIFs optimized for Slack, with validators for size constraints and composable animation primitives. This skill applies when users request animated GIFs or emoji animations for Slack from descriptions like \"make me a GIF for Slack of X doing Y\".","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FSKILL.md",[],[]]