Agent skill

Rust

by pgdogdev in pgdogdev/pgdog

Rust coding best practices for idiomatic, efficient, and maintainable code.

AGPL-3.0Auto-check: notesDatabases

Install Rust

skills CLI
$ npx skills add pgdogdev/pgdog --skill rust -a claude-code

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

GitHub CLI
$ gh skill install pgdogdev/pgdog rust --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/pgdogdev/pgdog.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/rust .claude/skills/rust && 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
GitHub stars
5.6k
Token cost
~1.9k tokens
SKILL.md length
237 words
Files
1
Skills in repo
1
Repo updated
First seen
Licence
AGPL-3.0

At a glance

Rust coding best practices for idiomatic, efficient, and maintainable code.

  • Works in 4 steps: Leverage the type system - Make invalid… → Prefer compile-time checks - Catch… → Be explicit about ownership - Don't… → …
  • Writing Rust code
  • SKILL.md covers Core Principles, Code health, Error Handling and Ownership & Borrowing, plus 6 more sections
  • Calls cargo

What it does

Rust is an agent skill from pgdogdev/pgdog. Rust coding best practices for idiomatic, efficient, and maintainable code. Use when writing Rust code, reviewing code, or learning Rust patterns.

Its SKILL.md is about 1.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 Databases, covering Cloud networking. It works with Rust and PostgreSQL. The repository describes itself as: PostgreSQL connection pooler, load balancer and database sharder. The licence is AGPL-3.0.

When your agent uses it

  • Writing Rust code
  • Learning Rust patterns

Example prompts

  • “/rust”

Requirements

  • Pre-approved tools (allowed-tools): Read, Edit, Write, Bash, Grep, Glob, Task

Workflow steps

4 steps, taken from the first numbered list in SKILL.md.

  1. Leverage the type system - Make invalid states unrepresentable
  2. Prefer compile-time checks - Catch errors before runtime
  3. Be explicit about ownership - Don't fight the borrow checker
  4. Write code that passes fmt/clippy first - Not after fixing

What it can do on your machine

Read from SKILL.md and the folder at commit a5de866. 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
    • Edit
    • Write
    • Bash
    • Grep
    • Glob
    • Task

    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 loads about 1.9k tokens when it runs. Until then it costs about 38 tokens; SKILL.md has 237 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~38
When it runs · the whole SKILL.md, loaded when a task matches
~1.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: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NotePre-approves every shell command (allowed-tools: Bash)SKILL.md
    allowed-tools: Read, Edit, Write, Bash, Grep, Glob, Task

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 pgdogdev/pgdog at commit a5de866, republished under its AGPL-3.0 licence (© pgdogdev). 237 words, ~1,891 tokens.

Download SKILL.mdSave it as .claude/skills/rust/SKILL.md (or your agent's skills folder).
name
rust
description
Rust coding best practices for idiomatic, efficient, and maintainable code. Use when writing Rust code, reviewing code, or learning Rust patterns.
allowed-tools
Read, Edit, Write, Bash, Grep, Glob, Task

Rust Best Practices

Guidelines for writing idiomatic, efficient, and maintainable Rust code.

Core Principles

  1. Leverage the type system - Make invalid states unrepresentable
  2. Prefer compile-time checks - Catch errors before runtime
  3. Be explicit about ownership - Don't fight the borrow checker
  4. Write code that passes fmt/clippy first - Not after fixing

Code health

  1. Prefer smaller files, refactor large files into multi-file modules
  2. Refactor large modules into several
  3. Prefer re-usable functions. Don't create separate functions if re-use is not planned.

Error Handling

Use thiserror

rust
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Failed to read config: {0}")]
    Io(#[from] std::io::Error),

    #[error("Failed to parse config: {0}")]
    Parse(#[from] toml::de::Error),

    #[error("Invalid configuration: {message}")]
    Invalid { message: String },
}
Never Use .unwrap()
rust
// BAD
let value = map.get("key").unwrap();

// GOOD
let value = map.get("key").ok_or_else(|| Error::MissingKey("key"))?;

// GOOD (when None is truly impossible)
let value = map.get("key").expect("key always present after init");

Ownership & Borrowing

Prefer Borrowing Over Cloning
rust
// BAD - unnecessary clone
fn process(data: String) { ... }
process(my_string.clone());

// GOOD - borrow when possible
fn process(data: &str) { ... }
process(&my_string);
Use Cow for Flexible Ownership
rust
use std::borrow::Cow;

fn process(data: Cow<'_, str>) -> Cow<'_, str> {
    if data.contains("bad") {
        Cow::Owned(data.replace("bad", "good"))
    } else {
        data  // No allocation if unchanged
    }
}
Return Owned Data from Constructors
rust
// GOOD - clear ownership
impl User {
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

API Design

Builder Pattern for Complex Configuration
rust
#[derive(Default)]
pub struct ServerBuilder {
    host: Option<String>,
    port: Option<u16>,
    timeout: Option<Duration>,
}

impl ServerBuilder {
    pub fn host(mut self, host: impl Into<String>) -> Self {
        self.host = Some(host.into());
        self
    }

    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    pub fn build(self) -> Result<Server, ConfigError> {
        Ok(Server {
            host: self.host.unwrap_or_else(|| "localhost".into()),
            port: self.port.ok_or(ConfigError::MissingPort)?,
            timeout: self.timeout.unwrap_or(Duration::from_secs(30)),
        })
    }
}
Newtype Pattern for Type Safety
rust
// BAD - easy to mix up
fn transfer(from: i64, to: i64, amount: i64) { ... }

// GOOD - compile-time safety
pub struct AccountId(i64);
pub struct Amount(i64);

fn transfer(from: AccountId, to: AccountId, amount: Amount) { ... }
Use #[must_use] for Important Returns
rust
#[must_use]
pub fn validate(&self) -> Result<(), ValidationError> {
    // ...
}

Collections & Iterators

Prefer Iterators Over Loops
rust
// BAD
let mut results = Vec::new();
for item in items {
    if item.is_valid() {
        results.push(item.transform());
    }
}

// GOOD
let results: Vec<_> = items
    .into_iter()
    .filter(|item| item.is_valid())
    .map(|item| item.transform())
    .collect();
Use collect() Type Inference
rust
// Collect into Vec
let vec: Vec<_> = iter.collect();

// Collect into HashMap
let map: HashMap<_, _> = iter.collect();

// Collect Results
let results: Result<Vec<_>, _> = iter.collect();

Async Patterns

Use tokio for Async Runtime
rust
#[tokio::main]
async fn main() -> Result<()> {
    let result = fetch_data().await?;
    Ok(())
}
Avoid Blocking in Async Code
rust
// BAD - blocks the runtime
async fn bad() {
    std::thread::sleep(Duration::from_secs(1));
}

// GOOD - async sleep
async fn good() {
    tokio::time::sleep(Duration::from_secs(1)).await;
}

// GOOD - spawn blocking for CPU-intensive work
async fn compute() -> i32 {
    tokio::task::spawn_blocking(|| expensive_computation()).await.unwrap()
}

Testing

Unit Tests in Same File
rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic() {
        assert_eq!(add(1, 2), 3);
    }

    #[test]
    fn test_edge_case() {
        assert!(validate("").is_err());
    }
}
Integration Tests in tests/
rust
// tests/integration_test.rs
use my_crate::public_api;

#[test]
fn test_full_workflow() {
    let result = public_api::process("input");
    assert!(result.is_ok());
}
Use assert! Macros Effectively
rust
assert!(condition);
assert_eq!(left, right);
assert_ne!(left, right);
assert!(result.is_ok());
assert!(result.is_err());
assert_matches!(value, Pattern::Variant { .. });

Performance

Avoid Premature Allocation
rust
// BAD - allocates even if not needed
fn maybe_string() -> String {
    String::from("default")
}

// GOOD - return static str when possible
fn maybe_string() -> &'static str {
    "default"
}
Use Vec::with_capacity for Known Sizes
rust
// BAD - multiple reallocations
let mut vec = Vec::new();
for i in 0..1000 {
    vec.push(i);
}

// GOOD - single allocation
let mut vec = Vec::with_capacity(1000);
for i in 0..1000 {
    vec.push(i);
}
Import instead of using absolute paths
rust
/// BAD
let v = tokio::net::TcpStream::connect("localhost:8080");

/// GOOD
use tokio::net::TcpStream;
let v = TcpStream::connect("localhost:8080");
Profile Before Optimizing
bash
cargo build --release
cargo flamegraph  # requires cargo-flamegraph

Module Organization

Keep Modules Focused
rust
// src/lib.rs
pub mod config;
pub mod client;
pub mod error;

// Re-export public API
pub use config::Config;
pub use client::Client;
pub use error::Error;
Use pub(crate) for Internal APIs
rust
// Public to crate, not external users
pub(crate) fn internal_helper() { ... }

Documentation

Document Public APIs
rust
/// Creates a new client with the given configuration.
///
/// # Arguments
///
/// * `config` - The client configuration
///
/// # Errors
///
/// Returns an error if the configuration is invalid.
///
/// # Examples
///
/// ```
/// let client = Client::new(Config::default())?;
/// ```
pub fn new(config: Config) -> Result<Self> {
    // ...
}

Anti-Patterns to Avoid

Anti-PatternBetter Approach
.unwrap() everywhereUse ? operator
clone() to satisfy borrow checkerRestructure ownership
String parametersUse &str or impl Into<String>
Boolean parametersUse enums
Long function bodiesExtract to smaller functions
Deep nestingUse early returns
Magic numbersUse named constants

Quick Reference

bash
# Quality gates
cargo fmt -- --check && cargo clippy -- -D warnings && cargo test

# Common cargo commands
cargo check           # Fast syntax/type check
cargo build           # Debug build
cargo build --release # Release build
cargo nextest run     # Run tests
cargo doc --open      # Generate and view docs
cargo clippy --fix    # Auto-fix lint issues

© pgdogdev, AGPL-3.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 .claude/skills/rust of pgdogdev/pgdog.

Open the folder on GitHubat commit a5de866

Compare with similar skills

Rust 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 compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Rust this skillpgdogdev/pgdog5.6k—~1.9kAutomated safety check: NotesAGPL-3.0
Monstermq Broker Configvogler75/monster-mq142—~2.2kAutomated safety check: PassGPL-3.0
Azure Resource Manager Postgresql Dotnetmicrosoft/skills3.1k6 repos~4kAutomated safety check: PassMIT
Fly Io DeployerLeoYeAI/openclaw-master-skills2.2k—~6.3kAutomated safety check: NotesMIT
Diesel Guardayarotsky/diesel-guard121—~3.1kAutomated safety check: PassMIT
cargo-pgrx Commands and Testsyugabyte/yugabyte-db11k—~1.9kAutomated safety check: PassCustom licence

Similar skills

  • Monstermq Broker Config

    vogler75/monster-mq

    Guide for configuring, deploying, and operating the MonsterMQ broker.

    142 GitHub stars~2.2k tokensUpdated yesterday
    DevOps & CloudAuto-check passed
  • Azure PostgreSQL Flexible Server SDK for .NET. An agent skill from microsoft/skills.

    3.1k GitHub starsUsed in 6 repos~4k tokens
    DevOps & CloudAuto-check passed
  • Fly Io Deployer

    LeoYeAI/openclaw-master-skills

    Deploy and operate Node, Python, Go, Rust, Elixir, and Docker apps on Fly.io with production-grade fly.toml authoring, Machines API orchestration, region selection (latency vs sovereignty vs…

    2.2k GitHub stars~6.3k tokensUpdated 2 mo ago
    DevOps & CloudAuto-check: notes
  • Diesel Guard

    ayarotsky/diesel-guard

    Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks.

    121 GitHub stars~3.1k tokensUpdated 9 days ago
    DatabasesAuto-check passed
  • cargo-pgrx Commands and Tests

    yugabyte/yugabyte-db

    Helps choose and run cargo-pgrx commands and decide whether a Rust test is a plain test or a pg_test, so code never crosses the Postgres boundary the wrong way.

    11k GitHub stars~1.9k tokensUpdated today
    Testing & QAAuto-check passed
  • Guides scalability and performance work for VeloxDB's Tauri + Rust PostgreSQL backend and React + TanStack frontend.

    646 GitHub stars~1.7k tokensUpdated 7 days ago
    DatabasesAuto-check passed

Works with

Questions about Rust

What does Rust do?

Rust coding best practices for idiomatic, efficient, and maintainable code. Rust is an agent skill from pgdogdev/pgdog. Rust coding best practices for idiomatic, efficient, and maintainable code.

When should I use Rust?

Rust fits situations like: writing Rust code; learning Rust patterns.

How do I install Rust in Claude Code?

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

How do I install Rust in Codex?

Run `npx skills add pgdogdev/pgdog --skill rust -a codex`. Or copy the skill folder (.claude/skills/rust in pgdogdev/pgdog) into .agents/skills/rust in your project. Codex loads it when a task matches its description.

Can I use Rust 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 pgdogdev/pgdog --skill rust -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, .gemini/skills/rust, .github/skills/rust and .opencode/skills/rust in your project.

What does Rust need to run?

Going by SKILL.md and its folder, Rust needs the command-line tools its instructions call (cargo). Its frontmatter pre-approves these tools: Read, Edit, Write, Bash, Grep, Glob, Task.

Does Rust 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 safe to install?

Our automated static check of SKILL.md found notes only (pre-approves every shell command (allowed-tools: bash)), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Rust use?

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

How many tokens does Rust use?

About 1.9k tokens (SKILL.md is roughly 7.6k 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?

Skills that share tags, products or a category with Rust: Monstermq Broker Config (vogler75/monster-mq, 142 stars), Azure Resource Manager Postgresql Dotnet (microsoft/skills, 3.1k stars), Fly Io Deployer (LeoYeAI/openclaw-master-skills, 2.2k stars) and Diesel Guard (ayarotsky/diesel-guard, 121 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Rust?

pgdogdev (a GitHub organization) maintains it in pgdogdev/pgdog, which has 5,552 GitHub stars. The repository was last updated on October 7, 2026.

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