rust-api-design
Skill1 starsChanged 6 months agoMITView on GitHub
Rust API Design guidelines, naming conventions, and best practices. Use when: - User is designing a library, crate, or public APIs - Implementing patterns like Builder, Typestate, or Extension traits - Designing public structures, enums, or traits - Working with common traits (From/Into, Default, AsRef, Debug, Clone) - Applying #[must_use] or #[non_exhaustive] attributes - Restricting trait implementation via Sealed Traits - Formatting naming structures and lifetime designs
6 other projects use a version of this.
Adopted by
Most recently taken up by
- takurot/rust-skills-comprehensivetheir own version, first seen Oct 15, 2026
- full-stack-skills/rust-skillstheir own version, first seen Oct 15, 2026
- Lu1sDV/skillsmdtheir own version, first seen Oct 13, 2026
- rcore-os/tgoskitstheir own version, first seen Oct 8, 2026
- jscott3201/yet-more-skillstheir own version, first seen Sep 7, 2026
- botirkhaltaev/botir-skillstheir own version, first seen Jul 24, 2026
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- rcore-os/tgoskits★ 76same name
- full-stack-skills/rust-skills★ 8same name
- botirkhaltaev/botir-skills★ 4same name
- jscott3201/yet-more-skills★ 4same name
- Lu1sDV/skillsmd★ 2same name
- takurot/rust-skills-comprehensive★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository24 other files it gives its agents.
- rust-asyncSkill
- rust-axumSkill
- rust-cliSkill
- rust-cloud-nativeSkill
- rust-concurrencySkill
- rust-databaseSkill
- rust-dioxusSkill
- rust-ecosystemSkill
- rust-embeddedSkill
- rust-error-handlingSkill
- rust-fintechSkill
- rust-masterySkill
- rust-memory-optimizationSkill
- rust-mlSkill
- rust-networkingSkill
- rust-observabilitySkill
- rust-ownershipSkill
- rust-design-patternsSkill
- rust-performanceSkill
- rust-securitySkill
- rust-testingSkill
- rust-type-systemSkill
- rust-unsafeSkill
- rust-wasmSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
13 rules. 0 are common, 7 are distinctive, and 6 are very specific to this project.
0
Common
Most of the 5 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 28
Use the type system to enforce valid state transitions at compile time instead of running checks at runtime.
- Very specific: line 57
Use builder structs to handle complex creation logic, and mark the build step with #[must_use].
- Distinctive: line 114
Add methods to external types without violating orphan rules.
- Very specific: line 157
Implement
Default: If a struct provides a parameterless new(), implement Default to match idiomatic conventions. - Very specific: line 158
AsRefandBorrow: Use AsRef<T> for cheap conversions to reference types, and reserve Borrow<T> for cases where the target has matching … - Very specific: line 160
Derive
Clone&PartialEq: when logical to do so, facilitating tests and standard collection handling. - Distinctive: line 166
Use strict API discipline for anything exported from a crate boundary.
- Distinctive: line 178
Use generics for zero-cost static dispatch and trait objects for runtime-selected behavior.
- Very specific: line 187
Use new for required arguments only.
- Very specific: line 233
Don't hide blocking work behind async fn.
- Distinctive: line 245
Keep the default feature set minimal.
- Distinctive: line 262
All public errors are typed and documented.
- Distinctive: line 312
When reviewing Rust API design, inspect naming, ownership, error types, semver stability, feature flags, and whether invalid states can be …
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Quick Navigation
- references/guidelines.md
- references/attributes.md
Rust API Design Guidelines
Expert guide for designing idiomatic, clean, robust, and forward-compatible APIs in Rust.
Core Rules & Patterns
1. Typestate Pattern
Use the type system to enforce valid state transitions at compile time instead of running checks at runtime.
// States
pub struct Draft;
pub struct Sent;
pub struct Email<State> {
recipient: String,
body: String,
_marker: std::marker::PhantomData<State>,
}
impl Email<Draft> {
pub fn new(recipient: String, body: String) -> Self {
Self { recipient, body, _marker: std::marker::PhantomData }
}
pub fn send(self) -> Email<Sent> {
Email {
recipient: self.recipient,
body: self.body,
_marker: std::marker::PhantomData,
}
}
}2. Builder Pattern
Use builder structs to handle complex creation logic, and mark the build step with #[must_use].
pub struct Server {
host: String,
port: u16,
}
#[derive(Default)]
pub struct ServerBuilder {
host: Option<String>,
port: Option<u16>,
}
impl ServerBuilder {
pub fn host(mut self, host: String) -> Self {
self.host = Some(host);
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
#[must_use = "builders must be executed to construct the target type"]
pub fn build(self) -> Result<Server, &'static str> {
let host = self.host.ok_or("Host required")?;
let port = self.port.unwrap_or(8080);
Ok(Server { host, port })
}
}3. Sealed Traits
Prevent downstream crates from implementing public traits by referencing a private marker trait.
mod private {
pub trait Sealed {}
}
// Seal the trait by requiring the private Sealed supertrait
pub trait SafeMath: private::Sealed {
fn safe_add(&self, other: &Self) -> Option<Self> where Self: Sized;
}
// Only implement for trusted types
impl private::Sealed for i32 {}
impl SafeMath for i32 {
fn safe_add(&self, other: &Self) -> Option<Self> {
self.checked_add(*other)
}
}4. Extension Traits
Add methods to external types without violating orphan rules.
pub trait StringExt {
fn is_alphanumeric_only(&self) -> bool;
}
impl StringExt for String {
fn is_alphanumeric_only(&self) -> bool {
self.chars().all(|c| c.is_alphanumeric())
}
}5. Parse, Don't Validate
Encode validity constraints into the type system itself to avoid repeated run-time checks.
// Bad: validates strings dynamically on every function call
fn process_email(email: &str) { ... }
// Good: parsing parses into a type-safe wrapper representing verified validity
pub struct EmailAddress(String);
impl std::str::FromStr for EmailAddress {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.contains('@') {
Ok(EmailAddress(s.to_string()))
} else {
Err("Invalid email format")
}
}
}6. Attribute Best Practices
#[must_use]: Annotate fallible or side-effect-free functions (e.g. builders, getters, calculations) to warn users when their outputs are ignored.#[non_exhaustive]: Annotate public enums and structs to allow adding new variants/fields in patch updates without breaking downstream crates.
7. Common Trait Implementations
- Prefer
FromoverInto: ImplementingFrom<T>automatically generatesInto<T>. Only implementIntowhen converting to external types whereFromcannot be implemented due to orphan rules. - Implement
Default: If a struct provides a parameterlessnew(), implementDefaultto match idiomatic conventions. AsRefandBorrow: UseAsRef<T>for cheap conversions to reference types, and reserveBorrow<T>for cases where the target has matching hash/equality semantics (e.g., hash keys).- Derive
Debug: Implement or deriveDebugon all public types to enable trouble-free integration and logging. - Derive
Clone&PartialEqwhen logical to do so, facilitating tests and standard collection handling.
Decision Rules
Public API vs Internal API
Use strict API discipline for anything exported from a crate boundary. Internal modules can move faster, but still keep invariants local.
// Public: stable, documented, forward-compatible
pub fn connect(config: ConnectConfig) -> Result<Client, ConnectError>;
// Internal: can be narrower and more direct
pub(crate) fn connect_with_parts(addr: SocketAddr, tls: TlsMode) -> io::Result<Socket>;Generic Parameter vs Trait Object
Use generics for zero-cost static dispatch and trait objects for runtime-selected behavior.
pub fn encode_with<C: Codec>(codec: C, data: &[u8]) -> Vec<u8> { codec.encode(data) }
pub fn encode_dyn(codec: &dyn Codec, data: &[u8]) -> Vec<u8> { codec.encode(data) }Builder vs Constructor
Use new for required arguments only. Use builders for optional parameters, validation, or future growth.
Newtype Pattern
// Strong typing prevents mixing unrelated IDs
pub struct UserId(pub Uuid);
pub struct OrderId(pub Uuid);
// These cannot be accidentally compared or swapped
// But still derive useful traits
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TenantId(pub Uuid);Error Type Design
#[derive(Debug, thiserror::Error)]
pub enum ConnectError {
#[error("address {addr} is not reachable")]
Unreachable { addr: SocketAddr },
#[error("TLS handshake failed")]
Tls(#[from] rustls::Error),
#[error("connection timed out after {0:?}")]
Timeout(Duration),
}
impl ConnectError {
/// True if the caller should retry.
pub fn is_retryable(&self) -> bool {
matches!(self, Self::Unreachable { .. } | Self::Timeout(_))
}
}Async API Patterns
// Good: async fn is clear about being async
pub async fn fetch_user(id: UserId) -> Result<User, Error> { /* ... */ }
// Good: generic over executor
pub async fn run_with<C: Executor>(client: &C) -> Result<(), Error> { /* ... */ }Don't hide blocking work behind async fn. Document if the method may block.
Feature Flag Design
[features]
default = ["json"]
json = ["serde", "serde_json"]
full = ["json", "grpc", "tls"]- Name features after capabilities, not crate names.
- Keep the default feature set minimal.
- Document feature interactions.
Naming Conventions
| Pattern | Convention | Example |
| Constructors | new() | Client::new() |
| Builders | builder() | Client::builder() |
| Getters | field name | client.host() |
| Setters | set_ prefix | client.set_host() |
| Boolean getters | is_, has_, can_ | client.is_connected() |
| Conversions | to_ / into_ / as_ | to_string() / into_inner() / as_ref() |
| Iterators | plural of item | users() returns impl Iterator<Item = &User> |
Production API Checklist
- All public errors are typed and documented.
- Constructors cannot create invalid values.
- Feature-gated APIs show
doc(cfg). - Public enums that may grow use
#[non_exhaustive]. - Panic behavior is documented or removed.
- Expensive operations are obvious from the name.
- Async APIs do not hide blocking work.
- Semver implications are considered before exposing fields.
- Newtypes prevent mixing of unrelated domain IDs.
- Builder methods consume and return
Self.
Common API Smells
Leaking Implementation Types
// Bad: exposes chosen hash map implementation
pub fn users(&self) -> &hashbrown::HashMap<UserId, User>;
// Better: expose behavior
pub fn get_user(&self, id: UserId) -> Option<&User>;
pub fn user_ids(&self) -> impl Iterator<Item = UserId> + '_;Boolean Parameter Traps
// Bad
client.connect(true, false);
// Better
client.connect(ConnectOptions { tls: TlsMode::Required, retry: RetryMode::Disabled });Overusing String
Accept &str for reading and impl Into<String> for storing.
Leaking Box<dyn Error>
// Bad: callers cannot match on specific errors
pub fn connect() -> Result<(), Box<dyn std::error::Error>>;
// Good: typed errors allow recovery
pub fn connect() -> Result<(), ConnectError>;Review Prompt
When reviewing Rust API design, inspect naming, ownership, error types, semver stability, feature flags, and whether invalid states can be constructed by safe callers.
References
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

