Skip to content
cccskills
FreePublished on GitHub

rust-systems

Apply common Rust systems programming patterns for ownership and borrowing, traits, async work, error handling, and configuration builders. The skill also highlights safer concurrency, reduced cloning, and documented invariants for any unsafe code.

OriginalShow the original description

Rust systems programming patterns including ownership, traits, async runtime, error handling, and unsafe guidelines

Run score Not tested

See how to install

Good for

  • Choosing borrowing or ownership in Rust
  • Designing reusable traits and error types
  • Reviewing async concurrency and unsafe code

Files included (1)

  • SKILL.md5.0 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

Rust Systems

Ownership and Borrowing

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

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

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

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

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

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Use this skill to make web interfaces more accessible. It provides patterns for semantic HTML, ARIA, keyboard navigation, forms, and color contrast, plus a checklist for evaluating WCAG AA accessibility with assistive technology.

  • Making menus and tabs keyboard accessible
  • Improving form labels and error announcements
  • Reviewing contrast and screen reader support
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

agentkit-seo

FreeSummary

Route broad SEO requests to the relevant platform module, such as LinkedIn, GitHub, or a CV. For work spanning several profiles or assets, it helps establish shared facts first and keeps the task focused on the needed context.

  • Choose a module for an unclear SEO request
  • Plan SEO work across LinkedIn and GitHub
  • Prepare shared facts before rewriting profile assets
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

Plan REST APIs with consistent resource URLs, HTTP methods, error responses, pagination, filtering, and versioning. It also covers writing an OpenAPI specification, a machine-readable API contract that can guide implementation and validation.

  • Choose resource URLs and HTTP methods for an API
  • Plan pagination and filtering for list endpoints
  • Draft an OpenAPI specification before implementation
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

Use this skill to plan or implement web authentication and access control. It covers JWT access and refresh tokens, OAuth2 with PKCE, sessions, and role-based permissions, with code examples and a checklist of common security practices.

  • Adding JWT access and refresh tokens to a web app
  • Setting up an OAuth2 login flow with PKCE
  • Restricting routes by user role
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

Build AWS application infrastructure using patterns for Lambda, DynamoDB, S3, and CDK. The examples cover API handlers, data access design, file event processing, and infrastructure settings, helping you shape cloud resources as code and avoid common setup mistakes.

  • Design a Lambda API with DynamoDB
  • Plan DynamoDB keys around query needs
  • Process files uploaded to S3
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

ci-cd-pipelines

FreeSummary

Create CI/CD workflows for GitHub Actions or GitLab CI that run validation, tests, builds, and deployments. Examples show job dependencies, caching, matrices, coverage reports, database services, and deployment gates to make automated delivery steps easier to organize.

  • Set up lint and test workflow jobs
  • Run tests across operating systems and versions
  • Build and deploy from the main branch
rohitg00/awesome-claude-code-toolkit2.7KUpdated May 12, 2026

See all skills by rohitg00

Report a problem with this skill