Skip to main content
skill CX Codex

rust-systems — Claude Code skill: Rust patterns and setup

This skill guides Rust systems code, from ownership and error handling to traits and async work. Use it when shaping a library or service.

Apache-2.0 ★ 2,858 updated 2026-05-12

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add rohitg00/awesome-claude-code-toolkit --skill rust-systems -a claude-code
Open on GitHub

What rust-systems does

The guidance favors borrowing over needless ownership transfers, uses thiserror to define library errors, and shows traits as seams for abstraction. Examples cover sqlx, tokio, and a Builder for server configuration.

Async sections show how to cap concurrent work and shut down a runtime gracefully. One important caveat: keeping a MutexGuard alive across .await can deadlock. The skill also calls for documenting safety invariants in unsafe blocks, avoiding .unwrap() in production paths, and addressing Clippy warnings.

What it helps with

  • replace unnecessary data clones with borrowing
  • define library errors with thiserror
  • cap concurrent async requests
  • abstract a repository behind a trait
  • document safety invariants in unsafe blocks

Example prompts for the agent

  • Review this Rust module for unnecessary clones and suggest where borrowing fits better.
  • Refactor the library's error handling to use thiserror and ?.
  • Limit concurrent requests in this async service and check for MutexGuard held across .await.

How to install rust-systems

1Skills CLI (Vercel)

npx skills add rohitg00/awesome-claude-code-toolkit --skill rust-systems -a claude-code

2Manually: put the files in place

~/.claude/skills/rust-systems/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/rust-systems/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about rust-systems

How do I install rust-systems in Claude Code?

Run npx skills add rohitg00/awesome-claude-code-toolkit --skill rust-systems -a claude-code. The skill file is at ~/.claude/skills/rust-systems/SKILL.md.

What does rust-systems do?

It provides Rust systems programming guidance on ownership, error types, traits, async patterns, builder-based configuration, and safe use of unsafe.

What async Rust pitfalls does rust-systems cover?

It warns that holding a MutexGuard across .await can cause deadlocks and recommends bounded concurrency with a semaphore or buffer_unordered.

Source text

SKILL.md · Apache-2.0
---
name: rust-systems
description: Rust systems programming patterns including ownership, traits, async runtime, error handling, and unsafe guidelines
---

# Rust Systems

## Ownership and Borrowing

```rust
fn process_data(data: &[u8]) -> Vec<u8> {
    data.iter().map(|b| b.wrapping_add(1)).collect()
}

fn modify_in_place(data: &mut Vec<u8>) {
    data.retain(|b| *b != 0);
    data.sort_unstable();
}

fn take_ownership(data: Vec<u8>) -> Vec<u8> {
    let mut result = data;
    result.push(0xFF);
    result
}

fn main() {
    let data = vec![1, 2, 3, 0, 4];
    let processed = process_data(&data);     // borrow: data still usable
    let mut owned = take_ownership(data);     // move: data no longer usable
    modify_in_place(&mut owned);              // mutable borrow
}
```

Prefer borrowing (`&T`, `&mut T`) over ownership transfer. Use `Clone` only when necessary.

## Error Handling

```rust
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("not found: {resource} with id {id}")]
    NotFound { resource: &'static str, id: String },

    #[error("validation failed: {0}")]
    Validation(String),
}

type Result<T> = std::result::Result<T, AppError>;

async fn get_user(pool: &PgPool, id: &str) -> Result<User> {
    sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
        .bind(id)
        .fetch_optional(pool)
        .await?
        .ok_or_else(|| AppError::NotFound {
            resource: "User",
            id: id.to_string(),
        })
}
```

Use `thiserror` for library errors, `anyhow` for application-level errors. Avoid `.unwrap()` in production code.

## Traits and Generics

```rust
trait Repository {
    type Item;
    type Error;

    async fn find_by_id(&self, id: &str) -> std::result::Result<Option<Self::Item>, Self::Error>;
    async fn save(&self, item: &Self::Item) -> std::result::Result<(), Self::Error>;
}

struct PgUserRepo {
    pool: PgPool,
}

impl Repository for PgUserRepo {
    type Item = User;
    type Error = AppError;

    async fn find_by_id(&self, id: &str) -> Result<Option<User>> {
        let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
            .bind(id)
            .fetch_optional(&self.pool)
            .await?;
        Ok(user)
    }

    async fn save(&self, user: &User) -> Result<()> {
        sqlx::query("INSERT INTO users (id, name, email) VALUES ($1, $2, $3)")
            .bind(&user.id)
            .bind(&user.name)
            .bind(&user.email)
            .execute(&self.pool)
            .await?;
        Ok(())
    }
}
```

## Async Patterns

```rust
use tokio::sync::Semaphore;
use futures::stream::{self, StreamExt};

async fn fetch_all(urls: Vec<String>, max_concurrent: usize) -> Vec<Result<String>> {
    let semaphore = Arc::new(Semaphore::new(max_concurrent));

    stream::iter(urls)
        .map(|url| {
            let sem = semaphore.clone();
            async move {
                let _permit = sem.acquire().await.unwrap();
                reqwest::get(&url).await?.text().await.map_err(Into::into)
            }
        })
        .buffer_unordered(max_concurrent)
        .collect()
        .await
}

async fn graceful_shutdown(handle: tokio::runtime::Handle) {
    let ctrl_c = tokio::signal::ctrl_c();
    ctrl_c.await.expect("Failed to listen for Ctrl+C");
    handle.shutdown_timeout(std::time::Duration::from_secs(30));
}
```

## Builder Pattern

```rust
pub struct ServerConfig {
    host: String,
    port: u16,
    workers: usize,
    tls: bool,
}

pub struct ServerConfigBuilder {
    host: String,
    port: u16,
    workers: usize,
    tls: bool,
}

impl ServerConfigBuilder {
    pub fn new() -> Self {
        Self { host: "0.0.0.0".into(), port: 8080, workers: 4, tls: false }
    }

    pub fn host(mut self, host: impl Into<String>) -> Self { self.host = host.into(); self }
    pub fn port(mut self, port: u16) -> Self { self.port = port; self }
    pub fn workers(mut self, n: usize) -> Self { self.workers = n; self }
    pub fn tls(mut self, enabled: bool) -> Self { self.tls = enabled; self }

    pub fn build(self) -> ServerConfig {
        ServerConfig { host: self.host, port: self.port, workers: self.workers, tls: self.tls }
    }
}
```

## Anti-Patterns

- Using `.unwrap()` or `.expect()` in library code
- Cloning data unnecessarily instead of borrowing
- Holding a `MutexGuard` across `.await` points (causes deadlocks)
- Using `Arc<Mutex<Vec<T>>>` when a channel would be more appropriate
- Writing `unsafe` without documenting invariants
- Not using `#[must_use]` on Result-returning functions

## Checklist

- [ ] Error types defined with `thiserror` and `?` operator used for propagation
- [ ] No `.unwrap()` in production paths
- [ ] Ownership model minimizes cloning
- [ ] Async code uses bounded concurrency (semaphores or `buffer_unordered`)
- [ ] Traits used for abstraction and testability
- [ ] `unsafe` blocks have documented safety invariants
- [ ] Builder pattern used for complex configuration structs
- [ ] Clippy lints enabled and warnings addressed

© rohitg00 · Apache-2.0 · rohitg00/awesome-claude-code-toolkit

Similar skills

All skills for Programming languages →

From the same set178

The whole set →
platform-engineer platform-engineer — a subagent for building internal developer platforms, configuring service mesh, observability, and managing SLOs. It helps cut developer cognitive load with golden path templates. CX Codex ★ 2,858repo stars penetration-tester penetration-tester is a Claude Code subagent for authorized security checks on web apps and APIs. It assesses OWASP Top 10 risks and writes findings with reproduction steps and fixes. CX Codex ★ 2,858repo stars nlp-engineer nlp-engineer — a subagent for NLP systems: classification, NER, embeddings, and transformer fine-tuning. Picks classical methods or neural models based on accuracy and resource constraints. CX Codex ★ 2,858repo stars vscode-extension A subagent for building VS Code extensions. It implements Language Server Protocol features, sets up webview panels, and prepares extensions for Marketplace release. CX Codex ★ 2,858repo stars ml-engineer ml-engineer is a Claude Code subagent for building machine learning pipelines from data preparation through model deployment. It handles work on training, evaluation, and monitoring. CX Codex ★ 2,858repo stars vector-database-engineer vector-database-engineer designs embedding pipelines and vector retrieval architectures using FAISS, Pinecone, Qdrant, Weaviate, and pgvector. Useful when tuning chunking, indexes, and hybrid search. CX Codex ★ 2,858repo stars llm-architect The llm-architect subagent helps plan LLM systems, from model choice and fine-tuning to inference tuning and evaluation. Use it when you need to compare candidates on your own data. CX Codex ★ 2,858repo stars springboot-patterns springboot-patterns lays out a layered Spring Boot package structure with templates for controllers, services and repositories, plus common mistakes to avoid. CX Codex +1 ★ 2,858repo stars

Project sponsors

Companies that keep this analytics open