[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AJZQ15G4SHXRDEMDRVRQYV":3,"skill-same:01M7AJZQ15G4SHXRDEMDRVRQYV":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},"01M7AJZQ15G4SHXRDEMDRVRQYV","rust-patterns",null,"Patrones idiomáticos de Rust, ownership, manejo de errores, traits, concurrencia y buenas prácticas para construir aplicaciones seguras y eficientes.","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\u002Fes\u002Fskills\u002Frust-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: rust-patterns\ndescription: Patrones idiomáticos de Rust, ownership, manejo de errores, traits, concurrencia y buenas prácticas para construir aplicaciones seguras y eficientes.\norigin: ECC\n---\n\n# Patrones de Desarrollo Rust\n\nPatrones idiomáticos y buenas prácticas de Rust para construir aplicaciones seguras, eficientes y mantenibles.\n\n## Cuándo Usar\n\n- Escribir código Rust nuevo\n- Revisar código Rust\n- Refactorizar código Rust existente\n- Diseñar la estructura de crates y la organización de módulos\n\n## Cómo Funciona\n\nEste skill refuerza las convenciones idiomáticas de Rust en seis áreas clave: ownership y borrowing para prevenir data races en tiempo de compilación, propagación de errores con `Result`\u002F`?` usando `thiserror` para bibliotecas y `anyhow` para aplicaciones, enums y pattern matching exhaustivo para hacer imposibles los estados inválidos, traits y genéricos para abstracciones de costo cero, concurrencia segura con `Arc\u003CMutex\u003CT>>`, canales y async\u002Fawait, y superficies `pub` mínimas organizadas por dominio.\n\n## Principios Fundamentales\n\n### 1. Ownership y Borrowing\n\nEl sistema de ownership de Rust previene data races y bugs de memoria en tiempo de compilación.\n\n```rust\n\u002F\u002F Bien: Pasar referencias cuando no se necesita el ownership\nfn process(data: &[u8]) -> usize {\n    data.len()\n}\n\n\u002F\u002F Bien: Tomar ownership solo cuando se necesita almacenar o consumir\nfn store(data: Vec\u003Cu8>) -> Record {\n    Record { payload: data }\n}\n\n\u002F\u002F Mal: Clonar innecesariamente para evitar el borrow checker\nfn process_bad(data: &Vec\u003Cu8>) -> usize {\n    let cloned = data.clone(); \u002F\u002F Costoso — solo tomar prestado\n    cloned.len()\n}\n```\n\n### Usar `Cow` para Ownership Flexible\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 Costo cero cuando no se necesita mutación\n    }\n}\n```\n\n## Manejo de Errores\n\n### Usar `Result` y `?` — Nunca `unwrap()` en Producción\n\n```rust\n\u002F\u002F Bien: Propagar errores con contexto\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 Mal: Causa panic en caso de error\nfn load_config_bad(path: &str) -> Config {\n    let content = std::fs::read_to_string(path).unwrap(); \u002F\u002F ¡Panic!\n    toml::from_str(&content).unwrap()\n}\n```\n\n### Errores de Biblioteca con `thiserror`, Errores de Aplicación con `anyhow`\n\n```rust\n\u002F\u002F Código de biblioteca: errores estructurados y tipados\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 Código de aplicación: manejo de errores flexible\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### Combinadores de `Option` en Lugar de Matching Anidado\n\n```rust\n\u002F\u002F Bien: Cadena de combinadores\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 Mal: Matching profundamente anidado\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 y Pattern Matching\n\n### Modelar Estados con Enums\n\n```rust\n\u002F\u002F Bien: Los estados imposibles son irrepresentables\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### Matching Exhaustivo — Sin Comodín en Lógica de Negocio\n\n```rust\n\u002F\u002F Bien: Manejar cada variante explícitamente\nmatch command {\n    Command::Start => start_service(),\n    Command::Stop => stop_service(),\n    Command::Restart => restart_service(),\n    \u002F\u002F Agregar una nueva variante fuerza su manejo aquí\n}\n\n\u002F\u002F Mal: El comodín oculta nuevas variantes\nmatch command {\n    Command::Start => start_service(),\n    _ => {} \u002F\u002F Ignora silenciosamente Stop, Restart y variantes futuras\n}\n```\n\n## Traits y Genéricos\n\n### Aceptar Genéricos, Retornar Tipos Concretos\n\n```rust\n\u002F\u002F Bien: Entrada genérica, salida concreta\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 Bien: Bounds de traits para múltiples restricciones\nfn process\u003CT: Display + Send + 'static>(item: T) -> String {\n    format!(\"processed: {item}\")\n}\n```\n\n### Trait Objects para Dispatch Dinámico\n\n```rust\n\u002F\u002F Usar cuando se necesitan colecciones heterogéneas o sistemas de plugins\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 Usar genéricos cuando se necesita rendimiento (monomorfización)\nfn fast_process\u003CH: Handler>(handler: &H, request: &Request) -> Response {\n    handler.handle(request)\n}\n```\n\n### Patrón Newtype para Seguridad de Tipos\n\n```rust\n\u002F\u002F Bien: Tipos distintos previenen mezclar argumentos\nstruct UserId(u64);\nstruct OrderId(u64);\n\nfn get_order(user: UserId, order: OrderId) -> Result\u003COrder> {\n    \u002F\u002F No se pueden intercambiar accidentalmente user ID y order ID\n    todo!()\n}\n\n\u002F\u002F Mal: Fácil intercambiar argumentos\nfn get_order_bad(user_id: u64, order_id: u64) -> Result\u003COrder> {\n    todo!()\n}\n```\n\n## Structs y Modelado de Datos\n\n### Patrón Builder para Construcción Compleja\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 Uso: ServerConfig::builder(\"localhost\", 8080).max_connections(200).build()\n```\n\n## Iteradores y Closures\n\n### Preferir Cadenas de Iteradores sobre Bucles Manuales\n\n```rust\n\u002F\u002F Bien: Declarativo, 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 Mal: Acumulación imperativa\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### Usar `collect()` con Anotación de Tipo\n\n```rust\n\u002F\u002F Recolectar en diferentes tipos\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 Recolectar Results — cortocircuita al primer error\nlet parsed: Result\u003CVec\u003Ci32>, _> = strings.iter().map(|s| s.parse()).collect();\n```\n\n## Concurrencia\n\n### `Arc\u003CMutex\u003CT>>` para Estado Mutable Compartido\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### Canales para Paso de Mensajes\n\n```rust\nuse std::sync::mpsc;\n\nlet (tx, rx) = mpsc::sync_channel(16); \u002F\u002F Canal acotado con 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 Cerrar el sender para que el iterador rx termine\n\nfor msg in rx {\n    println!(\"{msg}\");\n}\n```\n\n### Async con 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 Lanzar tareas concurrentes\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## Código Unsafe\n\n### Cuándo Unsafe Es Aceptable\n\n```rust\n\u002F\u002F Aceptable: Frontera FFI con invariantes documentados (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: el llamador garantiza que ptr es válido y alineado\n    unsafe { &*ptr }\n}\n\n\u002F\u002F Aceptable: Ruta crítica de rendimiento con prueba de corrección\n\u002F\u002F SAFETY: index is always \u003C len due to the loop bound\nunsafe { slice.get_unchecked(index) }\n```\n\n### Cuándo Unsafe NO Es Aceptable\n\n```rust\n\u002F\u002F Mal: Usar unsafe para evadir el borrow checker\n\u002F\u002F Mal: Usar unsafe por conveniencia\n\u002F\u002F Mal: Usar unsafe sin un comentario Safety\n\u002F\u002F Mal: Hacer transmute entre tipos no relacionados\n```\n\n## Sistema de Módulos y Estructura de Crates\n\n### Organizar por Dominio, No por Tipo\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # Módulo de dominio\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # Módulo de dominio\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # Infraestructura\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # Pruebas de integración\n├── benches\u002F           # Benchmarks\n└── Cargo.toml\n```\n\n### Visibilidad — Exponer el Mínimo\n\n```rust\n\u002F\u002F Bien: pub(crate) para compartir internamente\npub(crate) fn validate_input(input: &str) -> bool {\n    !input.is_empty()\n}\n\n\u002F\u002F Bien: Re-exportar la API pública desde lib.rs\npub mod auth;\npub use auth::AuthMiddleware;\n\n\u002F\u002F Mal: Hacer todo pub\npub fn internal_helper() {} \u002F\u002F Debería ser pub(crate) o privado\n```\n\n## Integración con Herramientas\n\n### Comandos Esenciales\n\n```bash\n# Construir y verificar\ncargo build\ncargo check              # Verificación de tipos rápida sin codegen\ncargo clippy             # Lints y sugerencias\ncargo fmt                # Formatear código\n\n# Pruebas\ncargo test\ncargo test -- --nocapture    # Mostrar salida de println\ncargo test --lib             # Solo pruebas unitarias\ncargo test --test integration # Solo pruebas de integración\n\n# Dependencias\ncargo audit              # Auditoría de seguridad\ncargo tree               # Árbol de dependencias\ncargo update             # Actualizar dependencias\n\n# Rendimiento\ncargo bench              # Ejecutar benchmarks\n```\n\n## Referencia Rápida: Modismos Rust\n\n| Modismo | Descripción |\n|---------|-------------|\n| Tomar prestado, no clonar | Pasar `&T` en lugar de clonar a menos que se necesite el ownership |\n| Hacer estados ilegales irrepresentables | Usar enums para modelar solo estados válidos |\n| `?` en lugar de `unwrap()` | Propagar errores, nunca causar panic en biblioteca\u002Fproducción |\n| Parsear, no validar | Convertir datos no estructurados a structs tipados en la frontera |\n| Newtype para seguridad de tipos | Envolver primitivos en newtypes para prevenir intercambio de argumentos |\n| Preferir iteradores sobre bucles | Las cadenas declarativas son más claras y frecuentemente más rápidas |\n| `#[must_use]` en Results | Asegurar que los llamadores manejen los valores de retorno |\n| `Cow` para ownership flexible | Evitar asignaciones cuando el borrowing es suficiente |\n| Matching exhaustivo | Sin comodín `_` para enums críticos de negocio |\n| Superficie `pub` mínima | Usar `pub(crate)` para APIs internas |\n\n## Anti-Patrones a Evitar\n\n```rust\n\u002F\u002F Mal: .unwrap() en código de producción\nlet value = map.get(\"key\").unwrap();\n\n\u002F\u002F Mal: .clone() para satisfacer el borrow checker sin entender por qué\nlet data = expensive_data.clone();\nprocess(&original, &data);\n\n\u002F\u002F Mal: Usar String cuando &str es suficiente\nfn greet(name: String) { \u002F* debería ser &str *\u002F }\n\n\u002F\u002F Mal: Box\u003Cdyn Error> en bibliotecas (usar thiserror en su lugar)\nfn parse(input: &str) -> Result\u003CData, Box\u003Cdyn std::error::Error>> { todo!() }\n\n\u002F\u002F Mal: Ignorar advertencias must_use\nlet _ = validate(input); \u002F\u002F Descartando silenciosamente un Result\n\n\u002F\u002F Mal: Bloquear en contexto async\nasync fn bad_async() {\n    std::thread::sleep(Duration::from_secs(1)); \u002F\u002F ¡Bloquea el executor!\n    \u002F\u002F Usar: tokio::time::sleep(Duration::from_secs(1)).await;\n}\n```\n\n**Recuerda**: Si compila, probablemente es correcto — pero solo si evitas `unwrap()`, minimizas `unsafe` y dejas que el sistema de tipos trabaje para ti.\n","# Patrones de Desarrollo Rust\n\nPatrones idiomáticos y buenas prácticas de Rust para construir aplicaciones seguras, eficientes y mantenibles.\n\n## Cuándo Usar\n\n- Escribir código Rust nuevo\n- Revisar código Rust\n- Refactorizar código Rust existente\n- Diseñar la estructura de crates y la organización de módulos\n\n## Cómo Funciona\n\nEste skill refuerza las convenciones idiomáticas de Rust en seis áreas clave: ownership y borrowing para prevenir data races en tiempo de compilación, propagación de errores con `Result`\u002F`?` usando `thiserror` para bibliotecas y `anyhow` para aplicaciones, enums y pattern matching exhaustivo para hacer imposibles los estados inválidos, traits y genéricos para abstracciones de costo cero, concurrencia segura con `Arc\u003CMutex\u003CT>>`, canales y async\u002Fawait, y superficies `pub` mínimas organizadas por dominio.\n\n## Principios Fundamentales\n\n### 1. Ownership y Borrowing\n\nEl sistema de ownership de Rust previene data races y bugs de memoria en tiempo de compilación.\n\n```rust\n\u002F\u002F Bien: Pasar referencias cuando no se necesita el ownership\nfn process(data: &[u8]) -> usize {\n    data.len()\n}\n\n\u002F\u002F Bien: Tomar ownership solo cuando se necesita almacenar o consumir\nfn store(data: Vec\u003Cu8>) -> Record {\n    Record { payload: data }\n}\n\n\u002F\u002F Mal: Clonar innecesariamente para evitar el borrow checker\nfn process_bad(data: &Vec\u003Cu8>) -> usize {\n    let cloned = data.clone(); \u002F\u002F Costoso — solo tomar prestado\n    cloned.len()\n}\n```\n\n### Usar `Cow` para Ownership Flexible\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 Costo cero cuando no se necesita mutación\n    }\n}\n```\n\n## Manejo de Errores\n\n### Usar `Result` y `?` — Nunca `unwrap()` en Producción\n\n```rust\n\u002F\u002F Bien: Propagar errores con contexto\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 Mal: Causa panic en caso de error\nfn load_config_bad(path: &str) -> Config {\n    let content = std::fs::read_to_string(path).unwrap(); \u002F\u002F ¡Panic!\n    toml::from_str(&content).unwrap()\n}\n```\n\n### Errores de Biblioteca con `thiserror`, Errores de Aplicación con `anyhow`\n\n```rust\n\u002F\u002F Código de biblioteca: errores estructurados y tipados\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 Código de aplicación: manejo de errores flexible\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### Combinadores de `Option` en Lugar de Matching Anidado\n\n```rust\n\u002F\u002F Bien: Cadena de combinadores\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 Mal: Matching profundamente anidado\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 y Pattern Matching\n\n### Modelar Estados con Enums\n\n```rust\n\u002F\u002F Bien: Los estados imposibles son irrepresentables\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### Matching Exhaustivo — Sin Comodín en Lógica de Negocio\n\n```rust\n\u002F\u002F Bien: Manejar cada variante explícitamente\nmatch command {\n    Command::Start => start_service(),\n    Command::Stop => stop_service(),\n    Command::Restart => restart_service(),\n    \u002F\u002F Agregar una nueva variante fuerza su manejo aquí\n}\n\n\u002F\u002F Mal: El comodín oculta nuevas variantes\nmatch command {\n    Command::Start => start_service(),\n    _ => {} \u002F\u002F Ignora silenciosamente Stop, Restart y variantes futuras\n}\n```\n\n## Traits y Genéricos\n\n### Aceptar Genéricos, Retornar Tipos Concretos\n\n```rust\n\u002F\u002F Bien: Entrada genérica, salida concreta\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 Bien: Bounds de traits para múltiples restricciones\nfn process\u003CT: Display + Send + 'static>(item: T) -> String {\n    format!(\"processed: {item}\")\n}\n```\n\n### Trait Objects para Dispatch Dinámico\n\n```rust\n\u002F\u002F Usar cuando se necesitan colecciones heterogéneas o sistemas de plugins\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 Usar genéricos cuando se necesita rendimiento (monomorfización)\nfn fast_process\u003CH: Handler>(handler: &H, request: &Request) -> Response {\n    handler.handle(request)\n}\n```\n\n### Patrón Newtype para Seguridad de Tipos\n\n```rust\n\u002F\u002F Bien: Tipos distintos previenen mezclar argumentos\nstruct UserId(u64);\nstruct OrderId(u64);\n\nfn get_order(user: UserId, order: OrderId) -> Result\u003COrder> {\n    \u002F\u002F No se pueden intercambiar accidentalmente user ID y order ID\n    todo!()\n}\n\n\u002F\u002F Mal: Fácil intercambiar argumentos\nfn get_order_bad(user_id: u64, order_id: u64) -> Result\u003COrder> {\n    todo!()\n}\n```\n\n## Structs y Modelado de Datos\n\n### Patrón Builder para Construcción Compleja\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 Uso: ServerConfig::builder(\"localhost\", 8080).max_connections(200).build()\n```\n\n## Iteradores y Closures\n\n### Preferir Cadenas de Iteradores sobre Bucles Manuales\n\n```rust\n\u002F\u002F Bien: Declarativo, 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 Mal: Acumulación imperativa\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### Usar `collect()` con Anotación de Tipo\n\n```rust\n\u002F\u002F Recolectar en diferentes tipos\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 Recolectar Results — cortocircuita al primer error\nlet parsed: Result\u003CVec\u003Ci32>, _> = strings.iter().map(|s| s.parse()).collect();\n```\n\n## Concurrencia\n\n### `Arc\u003CMutex\u003CT>>` para Estado Mutable Compartido\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### Canales para Paso de Mensajes\n\n```rust\nuse std::sync::mpsc;\n\nlet (tx, rx) = mpsc::sync_channel(16); \u002F\u002F Canal acotado con 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 Cerrar el sender para que el iterador rx termine\n\nfor msg in rx {\n    println!(\"{msg}\");\n}\n```\n\n### Async con 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 Lanzar tareas concurrentes\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## Código Unsafe\n\n### Cuándo Unsafe Es Aceptable\n\n```rust\n\u002F\u002F Aceptable: Frontera FFI con invariantes documentados (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: el llamador garantiza que ptr es válido y alineado\n    unsafe { &*ptr }\n}\n\n\u002F\u002F Aceptable: Ruta crítica de rendimiento con prueba de corrección\n\u002F\u002F SAFETY: index is always \u003C len due to the loop bound\nunsafe { slice.get_unchecked(index) }\n```\n\n### Cuándo Unsafe NO Es Aceptable\n\n```rust\n\u002F\u002F Mal: Usar unsafe para evadir el borrow checker\n\u002F\u002F Mal: Usar unsafe por conveniencia\n\u002F\u002F Mal: Usar unsafe sin un comentario Safety\n\u002F\u002F Mal: Hacer transmute entre tipos no relacionados\n```\n\n## Sistema de Módulos y Estructura de Crates\n\n### Organizar por Dominio, No por Tipo\n\n```text\nmy_app\u002F\n├── src\u002F\n│   ├── main.rs\n│   ├── lib.rs\n│   ├── auth\u002F          # Módulo de dominio\n│   │   ├── mod.rs\n│   │   ├── token.rs\n│   │   └── middleware.rs\n│   ├── orders\u002F        # Módulo de dominio\n│   │   ├── mod.rs\n│   │   ├── model.rs\n│   │   └── service.rs\n│   └── db\u002F            # Infraestructura\n│       ├── mod.rs\n│       └── pool.rs\n├── tests\u002F             # Pruebas de integración\n├── benches\u002F           # Benchmarks\n└── Cargo.toml\n```\n\n### Visibilidad — Exponer el Mínimo\n\n```rust\n\u002F\u002F Bien: pub(crate) para compartir internamente\npub(crate) fn validate_input(input: &str) -> bool {\n    !input.is_empty()\n}\n\n\u002F\u002F Bien: Re-exportar la API pública desde lib.rs\npub mod auth;\npub use auth::AuthMiddleware;\n\n\u002F\u002F Mal: Hacer todo pub\npub fn internal_helper() {} \u002F\u002F Debería ser pub(crate) o privado\n```\n\n## Integración con Herramientas\n\n### Comandos Esenciales\n\n```bash\n# Construir y verificar\ncargo build\ncargo check              # Verificación de tipos rápida sin codegen\ncargo clippy             # Lints y sugerencias\ncargo fmt                # Formatear código\n\n# Pruebas\ncargo test\ncargo test -- --nocapture    # Mostrar salida de println\ncargo test --lib             # Solo pruebas unitarias\ncargo test --test integration # Solo pruebas de integración\n\n# Dependencias\ncargo audit              # Auditoría de seguridad\ncargo tree               # Árbol de dependencias\ncargo update             # Actualizar dependencias\n\n# Rendimiento\ncargo bench              # Ejecutar benchmarks\n```\n\n## Referencia Rápida: Modismos Rust\n\n| Modismo | Descripción |\n|---------|-------------|\n| Tomar prestado, no clonar | Pasar `&T` en lugar de clonar a menos que se necesite el ownership |\n| Hacer estados ilegales irrepresentables | Usar enums para modelar solo estados válidos |\n| `?` en lugar de `unwrap()` | Propagar errores, nunca causar panic en biblioteca\u002Fproducción |\n| Parsear, no validar | Convertir datos no estructurados a structs tipados en la frontera |\n| Newtype para seguridad de tipos | Envolver primitivos en newtypes para prevenir intercambio de argumentos |\n| Preferir iteradores sobre bucles | Las cadenas declarativas son más claras y frecuentemente más rápidas |\n| `#[must_use]` en Results | Asegurar que los llamadores manejen los valores de retorno |\n| `Cow` para ownership flexible | Evitar asignaciones cuando el borrowing es suficiente |\n| Matching exhaustivo | Sin comodín `_` para enums críticos de negocio |\n| Superficie `pub` mínima | Usar `pub(crate)` para APIs internas |\n\n## Anti-Patrones a Evitar\n\n```rust\n\u002F\u002F Mal: .unwrap() en código de producción\nlet value = map.get(\"key\").unwrap();\n\n\u002F\u002F Mal: .clone() para satisfacer el borrow checker sin entender por qué\nlet data = expensive_data.clone();\nprocess(&original, &data);\n\n\u002F\u002F Mal: Usar String cuando &str es suficiente\nfn greet(name: String) { \u002F* debería ser &str *\u002F }\n\n\u002F\u002F Mal: Box\u003Cdyn Error> en bibliotecas (usar thiserror en su lugar)\nfn parse(input: &str) -> Result\u003CData, Box\u003Cdyn std::error::Error>> { todo!() }\n\n\u002F\u002F Mal: Ignorar advertencias must_use\nlet _ = validate(input); \u002F\u002F Descartando silenciosamente un Result\n\n\u002F\u002F Mal: Bloquear en contexto async\nasync fn bad_async() {\n    std::thread::sleep(Duration::from_secs(1)); \u002F\u002F ¡Bloquea el executor!\n    \u002F\u002F Usar: tokio::time::sleep(Duration::from_secs(1)).await;\n}\n```\n\n**Recuerda**: Si compila, probablemente es correcto — pero solo si evitas `unwrap()`, minimizas `unsafe` y dejas que el sistema de tipos trabaje para ti.\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fes\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\u002Fes\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",[],[]]