/rust-skills:rust-api-designfrom rust-skills
Designs public Rust crate APIs following the Rust API Guidelines naming, interop traits, type safety, and future-proofing conventions.
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 API Guidelines — the de-facto standard checklist of ~100 C-* rules used by std, tokio, serde, bevy. See the full checklist for canonical wording of every rule.
This skill owns the shape of a public Rust API: types, traits, naming, conversions, and the boundaries that keep the API usable, ergonomic, and resistant to breakage. It does not own Cargo manifest (rust-cargo-build), workspace topology (rust-workspace), in-crate src/ layout (rust-module-layout), or semver/publish (rust-semver).
From/Into/TryFrom/AsRef/Borrow conversions (rejecting Deref polymorphism)Debug, Clone, Eq, Hash, Send, Sync) to derive#[non_exhaustive], hiding struct fields — to reserve room to evolveString with &strExtend, Default, Display/FromStr correctlypanic!/unwrap/expect in public APIs in favor of Resultrust-stablerust-module-layout[features], optional = true — see rust-cargo-buildrust-semverrust-style-clippyrust-documentationrust-workspaceThis skill does not collect, store, or transmit user data.
The Guidelines are organized into 11 chapters. This skill owns 8 — the design chapters. Documentation, Macros, and Necessities live in rust-documentation, rust-macros, and rust-cargo-build respectively.
| Item | Case | Example |
|---|---|---|
| Types (struct/enum/trait), modules, crates | UpperCamelCase | HttpClient, tokio |
| Functions, methods, locals, fields | snake_case | send_request |
| Constants, statics | SCREAMING_SNAKE_CASE | MAX_RETRIES |
| Generic types | single UpperCamelCase letter or short word | T, K, V, Req |
| Lifetimes | short 'a/'b or descriptive 'src | 'src |
| Features | kebab-case (Cargo enforces) | serde-json |
Avoid ad-hoc abbreviations: BufferedReader is std-compliant; BufRdr is not.
| Conversion | Prefix | Borrows? | Example |
|---|---|---|---|
| Cheap, borrowed | as_ | Yes (&self → &T) | as_slice, as_bytes |
| Cheap, owned | to_ (no alloc) / into_ (consumes self) | Varies | to_vec, into_bytes |
| Expensive, returns new | to_ | No (&self → T) | to_lowercase |
| Consuming | into_ | No (self → T) | into_string, into_iter |
| Fallible | TryFrom/TryInto | — | u32::try_from(byte) |
Requirements: (1) A method named as_X that returns an owned X is wrong — rename to to_X. (2) The matched inverse for mutable borrows is as_X_mut / X_mut.
// ✅ C-GETTER compliant
pub struct Buffer { data: Vec<u8> }
impl Buffer {
pub fn data(&self) -> &[u8] { &self.data } // no get_ prefix
pub fn data_mut(&mut self) -> &mut [u8] { &mut self.data }
pub fn len(&self) -> usize { self.data.len() } // not get_len
pub fn is_empty(&self) -> bool { self.data.is_empty() }
}
Exceptions where get_ is allowed: Cell::get, Map::get (genuine lookup semantics).
For every public type, ask: should this derive Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default?
| Trait | Default | Exception |
|---|---|---|
Debug | Yes | Secrets → manual Debug that redacts |
Clone | Yes if cheap | Expensive clone → omit + document |
Copy | Only ≤16 bytes + lossless | — |
PartialEq/Eq | Yes if total order | f64 cannot be Eq |
Hash | Yes if Eq | Must agree with Eq |
Default | Yes if natural empty/zero | — |
From/Into/AsRef/Borrow; reject Deref polymorphism// ✅ Impl From<T> for U; Into comes for free
impl From<ErrorKind> for Error { fn from(k: ErrorKind) -> Self { Error::Kind(k) } }
// ✅ AsRef for borrowed views
impl AsRef<str> for Name { fn as_ref(&self) -> &str { &self.0 } }
// ✅ Borrow<str> if Eq/Hash should agree with str
impl Borrow<str> for Name { fn borrow(&self) -> &str { &self.0 } }
Reject Deref as polymorphism: Deref is for smart pointers (Box, Rc, Arc, String — std precedent). Using Deref to make MyClient transparent to HttpClient gives hidden method injection, breaks &self resolution, and is the deref polymorphism anti-pattern. Use AsRef, an explicit method, or composition.
// ✅ Provide IntoIterator for &T, &mut T, T when sensible
impl<'a> IntoIterator for &'a Grid {
type Item = &'a Cell;
type IntoIter = std::slice::Iter<'a, Cell>;
fn into_iter(self) -> Self::IntoIter { self.cells.iter() }
}
impl Grid {
pub fn iter(&self) -> impl Iterator<Item = &Cell> { /* */ }
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Cell> { /* */ }
}
impl Extend<Cell> for Grid { /* */ }
Rules: iter() borrows, iter_mut() mutably borrows, into_iter() consumes. Never return Vec from iteration methods — return impl Iterator.
#[serde(rename_all = "kebab-case")] consistently within a type#[non_exhaustive] enums need #[serde(other)] for forward compat with unknown variantsserde = ["dep:serde"]) so downstream can opt outIf the caller had to read the source to know what read does, the API is wrong. Don't surprise: a read method that panics on EOF is a defect.
const fn where possiblepub const fn new(value: u32) -> Self { Self(value) }
const fn is_power_of_two(n: u32) -> bool { n != 0 && n & (n - 1) == 0 }
Every std lib API that can be const fn is a candidate. Enables const MAX: UserId = UserId::new(1000); in callers.
Default and builderimpl Default for Config {
fn default() -> Self {
Config { retry_count: 3, timeout: Duration::from_secs(30) }
}
}
// Builder for complex construction
let client = Client::builder().with_retry(3).with_timeout(Duration::from_secs(10)).build()?;
// ✅ Generic over AsRef<str> — caller passes &str, String, Cow
pub fn parse(input: impl AsRef<str>) -> Result<Foo> { /* */ }
// ❌ Concrete &str — forces caller to borrow
pub fn parse(input: &str) -> Result<Foo> { /* */ }
Trade-off: more generics → longer compile, harder diagnostics. Generic on input types (AsRef<str>, IntoIterator); concrete on output.
// ✅ Newtypes around raw primitives
pub struct UserId(pub u64);
pub struct Email(String); // private inner — can't be constructed unsafely
fn delete_user(id: UserId) { /* */ } // can't accidentally pass a PostId
// ❌ Plain primitives — confusion and argument-order bugs
fn delete_user(id: u64) { /* */ }
Zero-cost (compile to the underlying type), prevent argument-order bugs, and allow attaching methods (UserId::is_anonymous()).
Ext suffixpub trait StringExt { fn slugify(&self) -> String; }
impl StringExt for str { fn slugify(&self) -> String { /* */ } }
// Caller opts in:
use my_crate::StringExt;
"Hello World".slugify();
Don't put methods directly on String/Vec/HttpRequest from other crates — use an Ext trait.
Authority: API Guidelines — Type Safety. See
references/api-guidelines-checklist.mdfor canonical wording.
// ✅ Enum — caller intent is explicit at call site
pub enum Trim { Whitespace, None }
pub fn parse(input: &str, trim: Trim) -> Result<Foo> { /* */ }
parse(" x ", Trim::Whitespace);
// ❌ Bool — caller must remember what true means
pub fn parse(input: &str, trim: bool) -> Result<Foo> { /* */ }
parse(" x ", true); // true = ??
Two bool params compound: f(true, false, true) is incomprehensible. Two-arg enums are the floor. Set clippy.toml max-fn-params-bools = 1 and max-struct-bools = 1 to enforce mechanically.
NonZeroUsize when zero is invaliduse std::num::NonZeroUsize;
// ✅ NonZeroUsize encodes "≥ 1" in the type
pub fn chunk_size(&self) -> NonZeroUsize { /* */ }
Enables niche optimization: Option<NonZeroU32> is the same size as u32. Use NonZeroU8/NonZeroU16/NonZeroU32/NonZeroU64/NonZeroUsize and the NonZeroI* variants.
&str not &String; &[T] not &Vec<T>// ✅ Borrow slices for inputs
pub fn process(data: &[u8], name: &str) { /* */ }
// ❌ Forces caller to have owned collections
pub fn process(data: &Vec<u8>, name: &String) { /* */ }
// ✅ u64 — semantically "count" can't be negative
pub struct Counter { count: u64 }
// ❌ i64 — implies negative values are valid (they aren't)
pub struct Counter { count: i64 }
For special ranges (e.g., Age 0..=150), use a newtype with validating constructor — let the type system prevent invalid values.
bitflags! macro for flag setsuse bitflags::bitflags;
bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Permissions: u32 {
const READ = 0b001;
const WRITE = 0b010;
const EXECUTE = 0b100;
}
}
let p = Permissions::READ | Permissions::WRITE; // type-checked composition
assert!(p.contains(Permissions::READ)); // built-in methods
Avoid raw u32 for flag sets — lose type safety, lose contains/insert/remove/intersects.
pub struct UserId(pub u64);
pub struct AccountId(pub u64);
pub struct OrderId(pub u64);
// Compiler rejects wrong-id bugs:
fn transfer(from: AccountId, to: AccountId, amount: Cents) { /* */ }
// transfer(UserId(1), UserId(2), Cents(100)) ← compile error
Zero-cost at runtime (compile to underlying type). Use #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] by default.
// ✅ Dedicated range type with validating constructor
pub struct ChunkRange { start: u32, end: u32 } // invariant: end >= start
impl ChunkRange {
pub fn new(start: u32, end: u32) -> Result<Self, RangeError> {
if end < start { return Err(RangeError::Inverted); }
Ok(Self { start, end })
}
pub fn contains(&self, x: u32) -> bool { self.start <= x && x <= self.end }
}
// ❌ Loose pair — caller might pass end < start
pub fn process_chunk(start: u32, end: u32) { /* */ }
For std ranges, use RangeInclusive/Range/RangeTo. For domain ranges (pagination, time windows), wrap in a newtype.
#[doc(hidden)] does NOT exclude from public API// ❌ Hides from rustdoc but is still semver-relevant
#[doc(hidden)]
pub mod unstable { /* */ } // downstream can still `use crate::unstable::Foo;`
// ✅ For actually-unstable items, gate behind a feature
#[cfg(feature = "unstable")]
pub mod unstable { /* */ }
#[doc(hidden)] only hides from cargo doc. For semver/stability, use feature flags or module privacy.
For owned inputs, accept String/Vec or impl Into<String>/impl IntoIterator.
// ✅ Documented, unreachable from public API
pub fn lookup(&self, id: UserId) -> &User {
self.table.get(&id).expect("internal: index invariant broken")
}
// ❌ Panics on user input
pub fn divide(a: f64, b: f64) -> f64 {
if b == 0.0 { panic!("division by zero") }
a / b
}
// ✅ Return Result for fallible operations
pub fn divide(a: f64, b: f64) -> Result<f64, DivError> { /* */ }
Acceptable: programmer violated an invariant, or function documented infallible. Unacceptable: input-driven failure.
unwrap/expect forbidden in public paths// ❌ Library code
pub fn parse(input: &str) -> Config {
serde_json::from_str(input).unwrap() // panics on bad input
}
// ✅ Propagate
pub fn parse(input: &str) -> Result<Config, ParseError> {
Ok(serde_json::from_str(input)?)
}
unwrap is OK in tests, const contexts (no ?), and proven-unreachable code. Use expect("reason") over bare unwrap() for diagnostics.
std::mem::transmute for type punningtransmute reinterprets bits, bypassing the type system. Use From/Into/TryFrom, bytemuck::cast/zerocopy (verified byte-cast), u64::from_ne_bytes/to_ne_bytes, or as for widening. If you reach for transmute, route to rust-unsafe-ffi.
Every public type implements Debug. Missing Debug blocks debugging; over-sharing in Debug leaks secrets.
#[derive(Debug)]
pub struct Client { /* */ }
// ✅ Manual Debug for secrets
impl std::fmt::Debug for Password {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Password(***)")
}
}
mod private { pub trait Sealed {} }
pub trait Serializer: private::Sealed {
fn serialize(&self, v: &impl Serialize);
}
pub struct JsonSerializer;
impl private::Sealed for JsonSerializer {}
impl Serializer for JsonSerializer { /* */ }
Without sealing, anyone can impl MyTrait for TheirType, locking you out of adding methods (would be a breaking change). See references/future-proofing.md.
// ✅ Private fields, public constructor — adding fields is non-breaking
pub struct Config { retry_count: u32, timeout: Duration }
impl Config {
pub fn new(retry: u32, timeout: Duration) -> Self { Self { retry_count: retry, timeout } }
pub fn builder() -> ConfigBuilder { /* */ }
}
// ❌ Pub fields + struct literal — adding a field breaks callers
let c = Config { retry_count: 3, timeout: Duration::from_secs(30) };
Rule: pub field = stable forever. Private field = evolvable.
#[non_exhaustive]
pub enum Error { Io(io::Error), Parse(ParseError) }
// Downstream must use a wildcard arm:
match err {
Error::Io(e) => /* */,
Error::Parse(e) => /* */,
_ => /* unknown */,
}
Use on error/event/status enums you intend to extend, and on structs with public fields you may add to.
cargo doc --open and list every pub item. That's the contract.as_/to_/into_), drop get_.Debug/Clone/etc., add From/AsRef, design iterators.Default, const fn, newtypes for primitives, Ext traits.NonZero*, &str over &String.unwrap/panic! from public paths; return Result.#[non_exhaustive] on growing enums, private struct fields.rust-semver; doctests → rust-documentation; lint config → rust-style-clippy.| Question | Answer |
|---|---|
Option or Result? | Option for "may not exist"; Result for "may fail" |
| Trait or enum? | Trait if open (others add impls); enum if closed (you own variants) |
| Generic or concrete? | Generic on input, concrete on output |
Field pub? | Default no. Only if struct-literal construction is intended |
&str or impl AsRef<str>? | AsRef<str> for flexibility; &str for simplicity |
Derive Copy? | Only if small (≤16 bytes) and bitwise copy is correct |
| Seal this trait? | Yes, unless third parties must add impls (rare) |
#[non_exhaustive]? | Yes for error/event enums; yes for structs with pub fields that may grow |
Deref polymorphism — Deref to "inherit" methods. Use composition.get_X accessors — drop get_. fn data(&self) -> &[u8].fn f(x: bool, y: bool). Use two enums.unwrap in public API — propagates panics. Use Result.String/Vec in inputs — forces ownership. Use &str/&[T].#[non_exhaustive] missing on errors — adding a variant breaks downstream.fn transfer(amount: u64, from: u64, to: u64) — argument order is a footgun.Debug leaking secrets — #[derive(Debug)] struct ApiKey(String). Custom redact.transmute for casts — use From/as/from_ne_bytes.See examples/anti-patterns.md for before/after refactors of each.
examples/golden-api/ — a small crate that follows every rule, cargo doc + clippy passingagents/openai.yaml (opens in a new tab)examples/anti-patterns.md (opens in a new tab)examples/golden-api/Cargo.lock (opens in a new tab)examples/golden-api/Cargo.toml (opens in a new tab)examples/golden-api/src/lib.rs (opens in a new tab)references/api-guidelines-checklist.md (opens in a new tab)references/future-proofing.md (opens in a new tab)references/naming-and-conversions.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
29 skills in this plugin
/rust-by-exampleShow Rust patterns through short compilable examples — type conversions (From/Into/TryFrom/as/Deref), flow control (if let/while let/match/loop), functions and closures (Fn/FnMut/FnOnce, captures), modules (mod/use/pub/super/self), generics and traits (bounds/associated types/trait objects), error handling (?/Result/thiserror/anyhow), attributes (derive/cfg/inline/allow), unsafe (raw pointers/unions/ABI), procedural macros (derive/attribute/function-like), and inline asm. Use when users ask "how do I write X in Rust", need a concrete pattern with copy-pasteable code, or are migrating from Java/Python/Go/C++ and want the Rust equivalent; hand architecture decisions to rust-api-design/rust-workspace, std API selection to rust-stdlib, and async runtime to rust-concurrency./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.Generated from the plugin's indexed repository (full-stack-skills/rust-skills) — no native marketplace selected
npx claudepluginhub p/full-stack-skills-rust-skillsOther plugins' skills for the same job