Agent skill

Rust Patterns

by softspark in softspark/ai-toolkit

Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe.

Apache-2.0Auto-check passedTesting & QA

Install Rust Patterns

skills CLI
$ npx skills add softspark/ai-toolkit --skill rust-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install softspark/ai-toolkit rust-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/rust-patterns .claude/skills/rust-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
rust-patterns
GitHub stars
179
Token cost
~2.9k tokens
SKILL.md length
192 words
Files
1
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe.

  • Testing & QA work in your project
  • SKILL.md covers Project Structure, Idioms / Code Style, Error Handling and Testing Patterns, plus 4 more sections
  • Calls cargo

What it does

Rust Patterns is an agent skill from softspark/ai-toolkit. Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe. Triggers: Rust, borrow checker, lifetime, Tokio, cargo, trait, impl, Result, unsafe, clippy.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Testing & QA. It works with Rust. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Testing & QA work in your project

Example prompts

  • “/rust-patterns”

Requirements

  • Docker
  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

Read from SKILL.md and the folder at commit d64db2b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • cargo

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Rust Patterns loads about 2.9k tokens when it runs. Until then it costs about 48 tokens; SKILL.md has 192 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~48
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 192 words, ~2,869 tokens.

Download SKILL.mdSave it as .claude/skills/rust-patterns/SKILL.md (or your agent's skills folder).
name
rust-patterns
description
Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe. Triggers: Rust, borrow checker, lifetime, Tokio, cargo, trait, impl, Result, unsafe, clippy.
allowed-tools
Read
effort
medium
user-invocable
false

Rust Patterns

Project Structure

my-app/
├── Cargo.toml
├── src/
│   ├── main.rs           # Binary entry point
│   ├── lib.rs            # Library root (re-exports)
│   ├── error.rs          # Crate-level error types
│   ├── api/
│   │   ├── mod.rs
│   │   └── handlers.rs
│   └── domain/
│       ├── mod.rs
│       └── service.rs
├── tests/                # Integration tests (separate crate)
│   └── api_test.rs
├── benches/              # criterion benchmarks
│   └── throughput.rs
└── examples/
    └── demo.rs

Workspace layout for multi-crate projects:

toml
# Cargo.toml (workspace root)
[workspace]
resolver = "2"
members = ["crates/core", "crates/api", "crates/cli"]

[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

Idioms / Code Style

Ownership and Borrowing
rust
// Borrow when you only need to read
fn print_name(name: &str) { println!("{name}"); }

// Take ownership when storing or consuming the value
fn register_user(name: String) -> User {
    User { name, id: Uuid::new_v4() }
}
Lifetimes
rust
// Annotate only when the compiler cannot infer
struct Parser<'input> {
    source: &'input str,
    pos: usize,
}

impl<'input> Parser<'input> {
    fn next_token(&mut self) -> Option<&'input str> {
        let start = self.pos;
        // ... advance self.pos ...
        Some(&self.source[start..self.pos])
    }
}
Trait-Based Design
rust
trait Repository {
    fn find_by_id(&self, id: Uuid) -> Result<Option<User>, DbError>;
    fn save(&self, user: &User) -> Result<(), DbError>;
}

// Accept generics for testability
fn create_user(repo: &impl Repository, name: String) -> Result<User, AppError> {
    let user = User::new(name);
    repo.save(&user)?;
    Ok(user)
}
Iterators, Pattern Matching, Newtype
rust
// Iterator chains over manual loops
let active: Vec<&str> = users.iter()
    .filter(|u| u.is_active)
    .map(|u| u.email.as_str())
    .collect();

// Exhaustive matching
match command {
    Command::Start { port } => start_server(port),
    Command::Stop => shutdown(),
}

// let-else for early exit (Rust 1.65+)
let Some(cfg) = load_config() else { return Ok(Config::default()); };

// Newtype to prevent primitive misuse
struct UserId(Uuid);
struct Email(String);

impl Email {
    fn new(raw: &str) -> Result<Self, ValidationError> {
        if raw.contains('@') { Ok(Self(raw.to_lowercase())) }
        else { Err(ValidationError::InvalidEmail) }
    }
}
Builder Pattern
rust
#[derive(Default)]
struct RequestBuilder { url: String, timeout: Option<Duration> }

impl RequestBuilder {
    fn url(mut self, url: impl Into<String>) -> Self { self.url = url.into(); self }
    fn timeout(mut self, d: Duration) -> Self { self.timeout = Some(d); self }
    fn build(self) -> Result<Request, BuildError> {
        if self.url.is_empty() { return Err(BuildError::MissingUrl); }
        Ok(Request { url: self.url, timeout: self.timeout.unwrap_or(Duration::from_secs(30)) })
    }
}

Error Handling

thiserror (libraries) vs anyhow (binaries)
rust
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AppError {
    #[error("not found: {0}")]
    NotFound(String),
    #[error("validation failed: {0}")]
    Validation(String),
    #[error("database error")]
    Database(#[from] sqlx::Error),
    #[error(transparent)]
    Unexpected(#[from] anyhow::Error),
}
rust
// anyhow for application / binary code -- adds context to any error
use anyhow::{Context, Result};

fn load_config(path: &Path) -> Result<Config> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    toml::from_str(&content).context("invalid TOML")
}
Error Propagation and Boundary Mapping
rust
// ? converts and propagates via From impls
fn get_email(pool: &PgPool, id: Uuid) -> Result<String, AppError> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(pool).await?
        .ok_or_else(|| AppError::NotFound(format!("user {id}")))?;
    Ok(user.email)
}

// Map domain errors to HTTP at the API boundary
impl IntoResponse for AppError {
    fn into_response(self) -> axum::response::Response {
        let (status, msg) = match &self {
            AppError::NotFound(m) => (StatusCode::NOT_FOUND, m.clone()),
            AppError::Validation(m) => (StatusCode::BAD_REQUEST, m.clone()),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, "internal error".into()),
        };
        (status, Json(json!({ "error": msg }))).into_response()
    }
}

Testing Patterns

Unit Tests (inline module)
rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn email_rejects_invalid() { assert!(Email::new("bad").is_err()); }

    #[tokio::test]
    async fn fetches_user() {
        let pool = setup_test_db().await;
        let user = get_user(&pool, test_id()).await.unwrap();
        assert_eq!(user.name, "Alice");
    }
}
Integration Tests (tests/ directory)
rust
// tests/api_test.rs -- compiled as separate crate, only sees pub API
#[tokio::test]
async fn health_returns_200() {
    let app = my_app::app().await;
    let resp = app.oneshot(
        Request::builder().uri("/health").body(Body::empty()).unwrap()
    ).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}
Mocking (mockall) and Property Testing (proptest)
rust
use mockall::automock;

#[automock]
trait UserRepo { fn find(&self, id: Uuid) -> Result<Option<User>, DbError>; }

#[test]
fn returns_not_found_when_missing() {
    let mut mock = MockUserRepo::new();
    mock.expect_find().returning(|_| Ok(None));
    assert!(matches!(UserService::new(mock).get_user(id), Err(AppError::NotFound(_))));
}
rust
use proptest::prelude::*;
proptest! {
    #[test]
    fn roundtrips(s in "[a-z]{1,20}@[a-z]{1,10}\\.[a-z]{2,4}") {
        let e = Email::new(&s).unwrap();
        assert_eq!(e.to_string(), s.to_lowercase());
    }
}
bash
cargo test                        # All tests
cargo test --lib                  # Unit only
cargo test --test api_test        # Single integration file
cargo nextest run                 # Parallel runner, better output

Common Libraries

CratePurposeNotes
serde / serde_jsonSerialization#[derive(Serialize, Deserialize)] on DTOs
tokioAsync runtimefeatures = ["full"] for apps
axumHTTP frameworkTower-based, extractors, State
clapCLI parsing#[derive(Parser)]
reqwestHTTP clientAsync, rustls TLS
tracingStructured loggingReplaces log; use tracing-subscriber
sqlxAsync SQLCompile-time checked queries
towerMiddlewareLayers, timeouts, rate limiting
rayonData parallelism.par_iter() drop-in
criterionBenchmarkingStatistical, HTML reports
Axum + Tracing Minimal Server
rust
use axum::{extract::State, routing::get, Json, Router};
use std::sync::Arc;

struct AppState { db: PgPool }

async fn list_users(State(s): State<Arc<AppState>>) -> Json<Vec<User>> {
    Json(sqlx::query_as!(User, "SELECT * FROM users")
        .fetch_all(&s.db).await.unwrap())
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .json().init();
    let pool = PgPool::connect(&std::env::var("DATABASE_URL").unwrap()).await.unwrap();
    let app = Router::new().route("/users", get(list_users)).with_state(Arc::new(AppState { db: pool }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Performance Tips

rust
// Avoid cloning -- return references when possible
fn names(data: &[Record]) -> Vec<&str> {
    data.iter().map(|r| r.name.as_str()).collect()
}

// Cow for conditional ownership -- zero alloc on the happy path
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
    if input.contains(' ') { Cow::Owned(input.replace(' ', "_")) }
    else { Cow::Borrowed(input) }
}

// Rayon for CPU-bound parallelism
use rayon::prelude::*;
let out: Vec<_> = inputs.par_iter().map(|i| compute(i)).collect();

// Preallocate collections
let mut v = Vec::with_capacity(items.len());

// Zero-cost abstractions: iterators compile to the same code as manual loops
let sum: u64 = values.iter().filter(|v| **v > 0).sum();

// #[inline] only on small hot functions crossing crate boundaries
Benchmarking (criterion)
rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn bench_parse(c: &mut Criterion) {
    let input = include_str!("../fixtures/large.json");
    c.bench_function("parse_json", |b| b.iter(|| parse(black_box(input))));
}
criterion_group!(benches, bench_parse);
criterion_main!(benches);

Build / Package Management

Cargo.toml
toml
[package]
name = "my-app"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"              # MSRV

[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
mockall = "0.13"

[[bench]]
name = "throughput"
harness = false
Feature Flags
toml
[features]
default = ["json"]
json = ["serde_json"]
postgres = ["sqlx/postgres"]
rust
#[cfg(feature = "postgres")]
pub mod pg_backend;
Release Profile
toml
[profile.release]
lto = true
codegen-units = 1
strip = true
panic = "abort"

[profile.dev.package."*"]
opt-level = 2                      # Optimize deps even in dev
Cross-Compilation
bash
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl
# Or use cross for Docker-based builds
cargo install cross && cross build --release --target aarch64-unknown-linux-gnu
Essential Cargo Commands
bash
cargo clippy -- -D warnings       # Lint (treat warnings as errors)
cargo fmt --check                  # Format check
cargo doc --open                   # Generate docs
cargo tree -d                      # Duplicate dependencies
cargo audit                        # Known vulnerabilities
cargo deny check                   # License and advisory
cargo bloat --release              # Binary size analysis
CI Pipeline (minimum)
bash
cargo fmt --check && cargo clippy -- -D warnings && cargo test && cargo audit

Anti-Patterns

Anti-PatternProblemFix
.unwrap() in lib codePanicsReturn Result/Option
.clone() everywhereHidden allocsBorrow, Cow, restructure ownership
String in every fieldUnnecessary allocs&str or Cow<str> where lifetime allows
Box<dyn Error> onlyNo matchingthiserror enums
Arc<Mutex<T>> firstContentionChannels (tokio::sync::mpsc) or actors
Ignoring #[must_use]Silent dropsHandle or let _ = explicitly

© softspark, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in app/skills/rust-patterns of softspark/ai-toolkit.

Open the folder on GitHubat commit d64db2b

Compare with similar skills

Rust Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Rust Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Rust Patterns this skillsoftspark/ai-toolkit179—~2.9kAutomated safety check: PassApache-2.0
Rust TDD Workflowrtk-ai/rtk83k—~753Automated safety check: NotesApache-2.0
Remote Executor Integration Testsopeninterpreter/openinterpreter69k2 repos~842Automated safety check: PassApache-2.0
Apple Container Test RunnerRustPython/RustPython22k—~467Automated safety check: PassMIT
RTK Filter TDD in Rustrtk-ai/rtk83k—~1.9kAutomated safety check: NotesApache-2.0
OpenLogi Device Fixture ContributionAprilNEA/OpenLogi23k—~1.2kAutomated safety check: PassApache-2.0

Similar skills

  • Enforces red-green-refactor for Rust work, with idiomatic test patterns, a naming convention and a pre-commit gate of cargo fmt, clippy and test.

    83k GitHub stars~753 tokensUpdated today
    Testing & QAAuto-check: notes
  • Remote Executor Integration Tests

    openinterpreter/openinterpreter

    Explains how to run agent integration tests against remote executors, using Docker for Linux or Wine for Windows, and how to opt tests in or skip them.

    69k GitHub starsUsed in 2 repos~842 tokens
    Testing & QAAuto-check passed
  • Apple Container Test Runner

    RustPython/RustPython

    Runs RustPython tests inside a Linux container built with Apple's container CLI, so macOS users can compare Linux results with their local ones.

    22k GitHub stars~467 tokensUpdated today
    Testing & QAAuto-check passed
  • Enforces red-green-refactor for new RTK output filters in Rust, using real captured fixtures, snapshot tests with insta and token-savings assertions.

    83k GitHub stars~1.9k tokensUpdated today
    Testing & QAAuto-check: notes
  • Guides recording, privacy review and offline verification of OpenLogi device fixtures with the fixture contribute and verify commands, without treating replay as proof of hardware behavior.

    23k GitHub stars~1.2k tokensUpdated 4 days ago
    Testing & QAAuto-check passed
  • Diagnoses a failed GreptimeDB fuzz CI job by pulling its GitHub Actions logs and fuzz artifacts, then matching the evidence to the local source code.

    6.7k GitHub stars~4.4k tokensUpdated 2 days ago
    Testing & QAAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated today
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated today
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated today
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated today
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated today
    Auto-check: notes

Works with

Categories

Questions about Rust Patterns

What does Rust Patterns do?

Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe. Rust Patterns is an agent skill from softspark/ai-toolkit. Rust: ownership, lifetimes, async (Tokio), Result/anyhow/thiserror, traits, unsafe.

When should I use Rust Patterns?

Rust Patterns fits situations like: testing & QA work in your project.

How do I install Rust Patterns in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill rust-patterns -a claude-code`. Or copy the skill folder (app/skills/rust-patterns in softspark/ai-toolkit) into .claude/skills/rust-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Rust Patterns in Codex?

Run `npx skills add softspark/ai-toolkit --skill rust-patterns -a codex`. Or copy the skill folder (app/skills/rust-patterns in softspark/ai-toolkit) into .agents/skills/rust-patterns in your project. Codex loads it when a task matches its description.

Can I use Rust Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add softspark/ai-toolkit --skill rust-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/rust-patterns, .gemini/skills/rust-patterns, .github/skills/rust-patterns and .opencode/skills/rust-patterns in your project.

What does Rust Patterns need to run?

Going by SKILL.md and its folder, Rust Patterns needs the command-line tools its instructions call (cargo). Our summary lists: Docker. Its frontmatter pre-approves these tools: Read.

Does Rust Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Rust Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Rust Patterns use?

Rust Patterns is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Rust Patterns use?

About 2.9k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Rust Patterns?

Skills that share tags, products or a category with Rust Patterns: Rust TDD Workflow (rtk-ai/rtk, 83k stars), Remote Executor Integration Tests (openinterpreter/openinterpreter, 69k stars), Apple Container Test Runner (RustPython/RustPython, 22k stars) and RTK Filter TDD in Rust (rtk-ai/rtk, 83k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Rust Patterns?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

Source: softspark/ai-toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.