/rust-skills:rust-by-examplefrom rust-skills
Provides compilable Rust code examples for common patterns: type conversions, flow control, closures, modules, generics, traits, error handling, attributes, unsafe, procedural macros, and inline assembly. Useful when users ask "how do I write X in Rust" or need concrete snippets.
Ships in rust-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Authority: Rust by Example — the official example-driven tutorial. This skill condenses its 24 chapters into a routing layer that points to topic-specific reference files.
This skill owns "how do I write X" patterns with concrete code. It does not own architectural decisions (rust-api-design, rust-workspace), language semantics (rust-stable), or std API selection (rust-stdlib).
From/Into/TryFrom/as/Deref/transmuteif let, while let, match, loop with labels, ?Fn/FnMut/FnOnce), capture modesuse, pub, super/self/crate, file-based module resolutionwhere clauses?, Result, Option, custom errors with thiserror, anyhow#[derive], #[cfg], #[inline], #[allow], #[non_exhaustive]unsafe fn/unsafe impl, unions, ABIrust-macros)core::arch::asm! (rare but supported)rust-stablerust-workspace, rust-module-layoutrust-api-designrust-workspace, rust-module-layoutrust-stdlibrust-concurrencyrust-unsafe-ffirust-macrosThis skill does not collect, store, or transmit user data.
Each section has a short example inline; deeper patterns live in the linked reference file.
// From / Into (lossless)
impl From<i32> for Wrapped { fn from(v: i32) -> Self { Self(v) } }
let w: Wrapped = 42.into(); // Into comes for free
// TryFrom (fallible)
impl TryFrom<&str> for Email {
type Error = EmailError;
fn try_from(s: &str) -> Result<Self, Self::Error> { /* */ }
}
// as (numeric widening/narrowing — can lose data)
let big: i64 = 1_000_000;
let small: i32 = big as i32; // ❌ silent truncation possible
// Deref (smart-pointer coercion, NOT polymorphism)
let s: String = "hi".to_string();
let s_ref: &str = &s; // Deref<Target=str> kicks in
See references/conversions.md for as vs From vs TryFrom, when each is correct.
// if let — single-pattern destructure
if let Some(x) = opt { /* */ }
// while let — loop until None
while let Some(line) = reader.lines().next() { /* */ }
// match with @-binding
match point {
Point { x: 0, y } => println!("on y-axis at {y}"),
Point { x, y: 0 } => println!("on x-axis at {x}"),
p @ Point { x: 10..=20, .. } => println!("in x-band: {p:?}"),
_ => {}
}
// loop with label
'outer: loop {
loop { break 'outer; }
}
See references/flow-control.md for match ergonomics, guards, ranges, and when to prefer if let.
// Closure captures by ref/move based on use
let v = vec![1, 2, 3];
let print = || println!("{:?}", v); // borrows
let consume = move || { v.into_iter().sum() }; // moves
// Fn / FnMut / FnOnce — how a closure borrows its environment
fn apply(f: impl Fn()) { f() } // can be called multiple times, immutable capture
fn apply_mut(mut f: impl FnMut()) { f() } // mutable capture
fn apply_once(f: impl FnOnce() -> i32) -> i32 { f() } // consumes captured
See references/closures.md for move keyword, return-type inference, and Fn/FnMut/FnOnce trait bounds.
// src/lib.rs
pub mod network; // src/network.rs OR src/network/mod.rs
pub use network::Client; // re-export
// src/network.rs
pub struct Client { /* */ }
pub fn connect() { /* */ }
// Using items
use std::collections::HashMap;
use std::io::{self, Read}; // io module + Read trait
use crate::network::Client; // absolute
use super::helper; // parent
use self::inner::Item; // current
See references/modules.md for pub/pub(crate)/pub(super), file-based vs mod.rs, and crate root re-exports. For deep layout work, route to rust-module-layout.
// Generic function with bound
fn first<T>(xs: &[T]) -> Option<&T> { xs.first() }
// Generic with where clause
fn sum<T>(xs: &[T]) -> T where T: Default + std::ops::AddAssign + Copy {
let mut acc = T::default();
for x in xs { acc += *x; }
acc
}
// Generic struct
struct Pair<A, B> { a: A, b: B }
impl<A: Clone, B: Clone> Pair<A, B> {
fn swapped(&self) -> Pair<B, A> { Pair { a: self.b.clone(), b: self.a.clone() } }
}
See references/generics-traits.md for monomorphization cost, when to use generics vs trait objects, and associated types vs generics.
// Definition with default method
pub trait Summary {
fn summarize(&self) -> String;
fn default_summary(&self) -> String { format!("(no summary)") }
}
// Trait object (dynamic dispatch)
fn print_summary(item: &dyn Summary) { println!("{}", item.summarize()); }
// Generic (static dispatch)
fn print_summary_generic<T: Summary>(item: &T) { println!("{}", item.summarize()); }
// Associated type
trait Container { type Item; fn first(&self) -> Option<&Self::Item>; }
Object safety rules: no Self in method signatures, no generic methods, sized receivers. See references/generics-traits.md.
use std::fs;
use std::io;
use std::num::ParseIntError;
// ? propagates with From conversion
fn read_count() -> Result<i32, io::Error> {
let s: String = fs::read_to_string("count.txt")?;
Ok(s.trim().parse().unwrap_or(0)) // or proper error mapping
}
// Custom error with thiserror
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("io: {0}")] Io(#[from] io::Error),
#[error("parse: {0}")] Parse(#[from] ParseIntError),
#[error("not found: {key}")] NotFound { key: String },
}
// Application-layer catch-all with anyhow
fn main() -> anyhow::Result<()> {
let x: i32 = "5".parse()?;
Ok(())
}
See references/error-handling.md for ? with From, thiserror vs anyhow, and custom error design.
#[derive(Debug, Clone, PartialEq)] // generate traits
struct User { id: u32 }
#[cfg(target_os = "linux")] // conditional compilation
fn setup() { /* */ }
#[inline] // hint to inline (rarely matters)
fn fast() {}
#[allow(dead_code)] // suppress warning
struct Unused;
#[non_exhaustive] // allow adding variants
enum Event { Login }
See references/attributes.md for the full attribute catalog, cfg expressions, and when #[inline] actually helps.
// Raw pointer dereference
let x = 42;
let ptr: *const i32 = &x;
let val = unsafe { *ptr };
// Splitting a slice (needs unsafe for non-overlapping aliasing)
let mut v = vec![1, 2, 3, 4];
let (left, right) = v.split_at_mut(2); // safe wrapper
// Calling C ABI
extern "C" { fn abs(input: i32) -> i32; }
let a = unsafe { abs(-5) };
// Union (unsafe to read)
#[repr(C)]
union Value { i: i32, f: f32 }
See references/unsafe.md for safety contracts, the four unsafe superpowers, and when to reach for it. For deep FFI, route to rust-unsafe-ffi.
// Derive (most common)
#[derive(Debug, Clone, serde::Serialize)]
struct Config { /* */ }
// Attribute macro
#[tokio::main]
async fn main() { /* */ }
// Function-like macro
let html = html! { <div>Hello</div> };
Authoring these is complex — route to rust-macros. This skill only covers using them.
See references/procedural-macros-overview.md for the three flavors and when each applies.
#[cfg(target_arch = "x86_64")]
fn halt() {
unsafe { std::arch::asm!("hlt", options(nostack)); }
}
See references/inline-asm.md for asm! syntax, clobbers, and when to use it (kernel/embedded only).
rust-stdlib; "how to architect" → rust-api-design.references/.cargo check, cargo clippy.| Question | Where |
|---|---|
| How do I convert types? | references/conversions.md |
How do I write if let/match? | references/flow-control.md |
| How do closures capture? | references/closures.md |
How do mod/use/pub work? | references/modules.md |
| Generic fn/struct/impl? | references/generics-traits.md |
| Trait object vs generic? | references/generics-traits.md |
| How do I propagate errors? | references/error-handling.md |
What #[derive]/#[cfg] are there? | references/attributes.md |
When is unsafe OK? | references/unsafe.md |
| How do I write a procedural macro? | rust-macros skill |
What does asm! look like? | references/inline-asm.md |
| Pattern in... | ...becomes in Rust |
|---|---|
| Java interface + impl | Rust trait + impl block |
Java generics <T extends Foo> | Rust <T: Foo> or where T: Foo |
Java Optional<T> | Rust Option<T> |
| Java try/catch | Rust ? + Result |
Python with | Rust Drop (RAII) |
| Python decorators | Rust attribute macros |
Go goroutine | Rust thread::spawn or async task |
Go interface{} | Rust dyn Trait or generics |
| C++ RAII destructor | Rust Drop trait |
C++ reinterpret_cast | Rust unsafe { transmute } (avoid) |
See references/migrating-from-other-languages.md for a fuller mapping.
examples/golden-by-example/: a crate exercising each patternagents/openai.yaml (opens in a new tab)examples/golden-by-example/Cargo.lock (opens in a new tab)examples/golden-by-example/Cargo.toml (opens in a new tab)examples/golden-by-example/src/lib.rs (opens in a new tab)references/attributes.md (opens in a new tab)references/closures.md (opens in a new tab)references/conversions.md (opens in a new tab)references/error-handling.md (opens in a new tab)references/flow-control.md (opens in a new tab)references/generics-traits.md (opens in a new tab)references/inline-asm.md (opens in a new tab)references/migrating-from-other-languages.md (opens in a new tab)references/modules.md (opens in a new tab)references/procedural-macros-overview.md (opens in a new tab)references/unsafe.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (full-stack-skills/rust-skills) — no native marketplace selected
npx claudepluginhub p/full-stack-skills-rust-skills29 skills in this plugin
/rust-api-designDesign Rust library APIs that follow the Rust API Guidelines — naming (C-CASE, C-CONV, C-GETTER), interop traits (C-COMMON-TRAITS, C-CONVERT, C-ITER, C-SERDE), predictability (C-INTUITIVE, C-CONST), flexibility (C-GENERIC, C-NEWTYPE, C-EXT), type safety (C-BOOL, C-NONZERO, C-WRAPPER, C-STR), dependability (C-PANIC, C-UNWRAP), debuggability (C-DEBUG), and future-proofing (C-SEALED, C-STRUCT-FIELD, C-NON-EXHAUSTIVE). Use when users design a public crate API, choose between generics/concrete/newtype, decide trait bounds, hide implementation, avoid breakage, or ask "what is idiomatic Rust API design"; hand semver and publish workflow to rust-semver, lint config to rust-style-clippy, and in-crate layout to rust-module-layout./rust-cargo-buildConfigure, operate, diagnose, and automate Cargo for Rust packages and workspaces. Cover manifests and targets, commands, dependency resolution and features, profiles, build scripts, configuration and environment variables, caches and build diagnostics, cross-compilation, registries, packaging, publishing, metadata, CI reproducibility, and stable-versus-nightly feature gates. Use for Cargo.toml, Cargo.lock, .cargo/config.toml, cargo build/check/run/tree/metadata/package/publish, resolver or feature problems, build output and performance, private registries, and beginner Cargo workflows. Route crate selection and supply-chain audits to rust-dependencies, workspace topology to rust-workspace, test design to rust-testing, documentation design to rust-documentation, lint policy to rust-style-clippy, and API compatibility decisions to rust-semver./rust-cliDesign, implement, test, and release production Rust command-line applications, including command contracts, subcommands, configuration precedence, stdin/stdout/stderr, exit codes, file safety, daemon IPC, terminal handling, packaging, and process-level tests. Use when users ask for a Rust CLI, command parser, clap integration, Unix-style pipelines, daemon clients, PTY/TUI behavior, shell completion, or CLI release engineering./rust-code-reviewReview Rust changes for correctness, memory and thread safety, error semantics, unnecessary allocation or cloning, lock scope, API compatibility, test gaps, documentation, and dependency risk, applying the Rust API Guidelines checklist (C-PANIC, C-UNWRAP, C-TRANSMUTE, C-BOOL, C-NEWTYPE, C-COMMON-TRAITS, C-CONVERT, C-SEALED, C-NON-EXHAUSTIVE). Use when reviewing Rust diffs, pull requests, libraries, unsafe boundaries, or production incidents; report actionable findings by severity before summaries, route automated formatting or lint policy to rust-style-clippy, and route API shape decisions (trait sealing, error taxonomy, newtype design, builder patterns) to rust-api-design./rust-concurrencyDesign, implement, diagnose, and test Rust concurrency and parallelism with threads, Send and Sync, locks, atomics, channels, Tokio, Rayon, Crossbeam, bounded backpressure, actor ownership, task supervision, graceful shutdown, runtime diagnostics, and Loom model tests. Use when users ask about shared state, deadlocks, async tasks, CPU parallelism, high concurrency, daemon resource budgets, slow consumers, worker pools, lock-free structures, or concurrent correctness./rust-crate-discoveryDiscover, evaluate, score, and compare Rust crates for adoption — search crates.io, fetch metadata from 4 sources (crates.io API, docs.rs, GitHub API, RustSec advisory DB), apply a weighted 0-100 scoring model across adoption/maintenance/documentation/maturity/community/license, flag red concerns (unmaintained, advisories, no docs, single-maintainer), and recommend the best fit. Use when users ask "which crate should I use for X", "is this crate maintained/safe/popular", "compare these 3 crates", or need to pick a dependency before adoption; hand post-adoption governance (cargo-deny, license policy, advisory response) to rust-dependencies, semver and breaking-change classification to rust-semver, and manifest mechanics to rust-cargo-build.Other plugins' skills for the same job