references/rust-api-guidelines.md
GitHubRust API Guidelines (digest)
Source: https://rust-lang.github.io/api-guidelines/ (official rust-lang project). Read this when designing or reviewing a public API or publishing a crate. All 54 checklist items are covered, grouped as in the original.
Naming
C-CASE:
UpperCamelCasefor types, traits, enum variants;snake_casefor modules, functions, methods, locals;SCREAMING_SNAKE_CASEfor consts and statics; short type params (T); short lowercase lifetimes ('a,'de). An acronym is one word inUpperCamelCase(Uuid,Stdin) and lowercased insnake_case(is_xid_start). Crate names never carry a-rsor-rustaffix.C-CONV: ad-hoc conversion prefixes:
Prefix Cost Ownership as_free borrowed -> borrowed to_expensive borrowed -> borrowed; borrowed -> owned (non-Copy); owned -> owned (Copy) into_variable owned -> owned (non-Copy) as_andinto_expose the representation;to_stays at the same abstraction level but does work (Path::to_strchecks UTF-8). Wrappers expose their value withinto_inner().mutgoes in type order:as_mut_slice.C-GETTER: no
get_prefix:first(&self) -> &First,first_mut(&mut self). Baregetonly when there is one obvious thing to get (Cell::get). Checked accessors getunsafe fn get_uncheckedsiblings.C-ITER: collections provide
iter(&self) -> Iter(items&U),iter_mut, andinto_iter(self) -> IntoIter. Non-homogeneous types (str) usebytes(),chars().C-ITER-TY: the iterator type is named after the method:
into_iter->IntoIter,keys->Keys,percent_encode->PercentEncode.C-FEATURE: feature names have no placeholder words:
abc, notuse-abc. Gate std asdefault = ["std"],std = [], with#![no_std]and#[cfg(feature = "std")] extern crate std;. Features are additive, sono-abcis almost always wrong.C-WORD-ORDER: be consistent with std: error types are verb-object-error (
ParseBoolError, soParseAddrError, notAddrParseError).
Interoperability
- C-COMMON-TRAITS: eagerly implement
Copy,Clone,Eq,PartialEq,Ord,PartialOrd,Hash,Debug,Display,Defaultwhere applicable. Orphan rules mean downstream crates cannot add them. Provide an emptynew()alongsideDefault, and make them behave identically. - C-CONV-TRAITS: implement
From,TryFrom,AsRef,AsMut. Never implementIntoorTryIntodirectly.From<u16> for u32for lossless,TryFrom<u32> for u16for fallible; neverFrom<u32> for u16. - C-COLLECT: collections implement
FromIterator<T>andExtend<T>socollect,partition, andunzipwork. - C-SERDE: data-structure types implement
Serialize/Deserializebehind an optional feature named exactlyserde:#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]. - C-SEND-SYNC:
SendandSyncare automatic; check them on types holding raw pointers and lock them in with a test:fn assert_send<T: Send>() {}thenassert_send::<MyType>();. - C-GOOD-ERR: any
Ein a publicResult<T, E>implementsstd::error::Errorand should beSend + Sync. Boxed errors areBox<dyn Error + Send + Sync + 'static>('staticenablesdowncast_ref). Never use()as an error type.Displaymessages are lowercase, concise, no trailing punctuation. Don't implement the deprecateddescription(). - C-NUM-FMT: number-like types you would combine with
|or&(bitflags) implementLowerHex,UpperHex,Octal,Binary. Quantities (Nanoseconds(u64)) don't need them. - C-RW-VALUE: generic functions take
R: ReadandW: Writeby value;&mut Ralso implementsRead, so callers pass&mut fto keep using it. Say so in the docs.
Macros
- C-EVOCATIVE: macro input resembles the output (
struct S: u32 { .. }, const-like items end in;). - C-MACRO-ATTR: macros that emit items accept attributes on each item, so
#[cfg(..)]and#[derive(..)]work. - C-ANYWHERE: item macros work at module and function scope; test both. Emitting
super::Ubreaks inside a function. - C-MACRO-VIS: emitted items are private unless the input says
pub. - C-MACRO-TY: a
$t:tyfragment accepts primitives, relative and absolute paths,super::, and generics. Don't emit a nestedpub modthat can't see local types.
Documentation
C-CRATE-DOC: crate-level docs are thorough and include examples.
C-EXAMPLE: every public module, trait, struct, enum, function, method, macro, and type alias has an example, within reason. Show why to use it, not mechanically how.
C-QUESTION-MARK: examples use
?, nevertry!orunwrap(), because users copy them verbatim. Hide the scaffolding with#lines:/// ``` /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// let value = parse_it("...")?; /// # Ok(()) /// # } /// ```C-FAILURE:
# ErrorswhenErrcan be returned (including trait methods whose impls may err);# Panicswhen a function can panic;# Safetyon everyunsafe fnlisting every caller invariant.C-LINK: link items in prose with
[`Type`].C-METADATA:
[package]hasauthors,description,license,repository,keywords,categories;documentationonly if not on docs.rs;homepageonly if distinct fromrepository.C-RELNOTES: keep release notes, mark breaking changes, and tag releases with annotated tags (
git tag -a).C-HIDDEN:
#[doc(hidden)]on impls users never trigger (From<PrivateError> for PublicErrorexists only to enable?). Usepub(crate)for internals.
Predictability
- C-SMART-PTR: smart pointers add no inherent methods; use associated functions
(
Box::into_raw(b), notb.into_raw()), so a call can't be ambiguous with the pointee. - C-CONV-SPECIFIC: put conversions on the more specific type (
str::as_bytes,str::from_utf8). Preferto_/as_/into_overfrom_; they chain better. - C-METHOD: if a function has a clear receiver, make it a method
(
impl Foo { fn frob(&self, w: Widget) }). Methods need no import, autoborrow, and express ownership throughself. - C-NO-OUT: return multiple values as a tuple or struct, not
&mutout-parameters. Exception: reusing a caller-owned buffer (Read::read). - C-OVERLOAD: implement
std::opstraits only when the operation resembles the operator and shares its properties (Mulshould be associative). - C-DEREF: only smart pointers implement
Deref/DerefMut. The coercion and method-resolution rules are designed for them (Box,String,Rc,Arc,Cow). - C-CTOR: constructors are static inherent methods. Primary is
new(); secondary ones take a_with_foosuffix (open_with_offset); I/O resources use domain names (File::open,TcpStream::connect); conversion constructors arefrom_fooand may beunsafe(Box::from_raw) or take extra args (u64::from_str_radix), unlikeFrom. Many options means a builder.
Flexibility
C-INTERMEDIATE: expose work already done.
binary_searchreports the insertion index on a miss;String::from_utf8's error returns the valid prefix length and the bytes;HashMap::insertreturns the old value.C-CALLER-CONTROL: if the function needs ownership, take by value and never clone a borrow internally. If it only reads or mutates, take
&/&mut. Bound byCopyonly when required, not to advertise cheapness.C-GENERIC: assume as little as possible. Iterating only?
fn foo<I: IntoIterator<Item = i64>>(iter: I), not&[i64].File::opentakesAsRef<Path>. Costs: code size, one concrete type per parameter, verbose signatures.C-OBJECT: decide early whether a trait is a bound or an object. Generic methods and
Selfoutside the receiver block object safety; exclude them withwhere Self: Sized:trait MyTrait { fn object_safe(&self, i: i32); fn not_object_safe<T>(&self, t: T) where Self: Sized; }
Type safety
- C-NEWTYPE:
struct Miles(pub f64)vsstruct Kilometers(pub f64)gives static distinctions at zero runtime cost. (The guide cites the Mars Climate Orbiter.) - C-CUSTOM-TYPE: don't pass
bool,u8, orOptionwhere meaning is ambiguous.Widget::new(Small, Round), notWidget::new(true, false). Enums can also grow later. - C-BITFLAG: independent flags use the
bitflagscrate; an enum models exactly one choice. Explicit discriminants suit serialization or C interop. - C-BUILDER: introduce
TBuilderwhen a type has many inputs, compound data, optional config, several flavors, or side effects on build. The constructor takes only required data, config methods chain, terminal methods build. Prefer non-consuming builders (&mut self -> &mut Self, terminal&self):Command::new("cat").arg("f").spawn(). Consuming builders only when the terminal method must move a value out.
Dependability
- C-VALIDATE: enforce validity, in preference order: statically (a type that rules
out bad input,
fn foo(a: Ascii)overfn foo(a: u8)), dynamically (check as you process,debug_assert!for expensive checks), opt-out (_uncheckedsiblings or arawmodule for confident callers). - C-DTOR-FAIL: destructors never fail; failing during unwinding aborts. Provide
close(self) -> Result<..>and letDropbe best-effort. - C-DTOR-BLOCK: destructors don't block. Offer a separate method that prepares an infallible, non-blocking teardown.
Debuggability
- C-DEBUG: all public types implement
Debug. Exceptions are rare. - C-DEBUG-NONEMPTY: even empty values produce non-empty
Debugoutput (""->"\"\"", empty vec ->"[]").
Future proofing
C-SEALED: the sealed trait pattern lets you add methods without breaking users:
pub trait TheTrait: private::Sealed { /* ... */ } impl TheTrait for usize { /* ... */ } mod private { pub trait Sealed {} impl Sealed for usize {} }Document that the trait is sealed.
C-STRUCT-PRIVATE: fields private by default; a public field fixes the representation and blocks invariants. Public fields only for passive C-style data.
C-NEWTYPE-HIDE: hide implementation types behind a newtype (
pub struct MyIter<I>(Enumerate<Skip<I>>)) so the inner type can change.impl Traitis more concise but awkward forDebug/Clonebounds; fine for internal APIs.C-STRUCT-BOUNDS: no derivable bounds on struct definitions.
#[derive(Clone, Debug, PartialEq)] struct Good<T>, notstruct Bad<T: Clone + Debug + PartialEq>. Never bound a data structure byClone,PartialEq,PartialOrd,Debug,Display,Default,Error,Serialize,Deserialize. Exceptions: associated-type references,?Sized, aDropimpl that needs the bound.
Necessities
- C-STABLE: a 1.0+ crate needs every public dependency (any crate whose types appear
in its API) to be stable too.
From<other_crate::Error>leaksother_crate. - C-PERMISSIVE:
license = "MIT OR Apache-2.0"with both license files, matching Rust itself. Depend only on permissively licensed crates.