This guide documents cross-project Rust conventions for module organization, imports, visibility, type design, error semantics, public API documentation, and testing. Standard formatting and baseline lints are delegated to rustfmt and clippy; the rules below cover deliberate choices where valid Rust styles diverge.
- File header order: Order the top of each module file as module documentation (
//!), ordinaryuseimports, out-of-linemoddeclarations (with any immediatepub use self::...re-exports), and module items. Placinguseblocks beforemoddeclarations ensures IDE and agent auto-imports append cleanly to existing import groups. - Directory modules: Organize multi-file modules under
<module>/mod.rsrather than mixing<module>.rswith a sibling<module>/directory. - File splitting restraint: Keep cohesive types and helpers in one file until a distinct responsibility emerges; a separate file does not by itself justify widening visibility boundaries. Extract a private companion file (such as
impls.rsfor repetitive trait forwarding or tuple macro implementations) only when isolating boilerplate clarifies the primary module. - Grouping
moddeclarations: Group out-of-linemoddeclarations by role, separated by a blank line and sorted alphabetically within each group:- Public modules (
pub mod ...;). - Private modules with public re-exports (
mod foo;followed immediately bypub use self::foo::...;). - Implementation-only private modules (
mod ...;), with out-of-line#[cfg(test)]modules last.
- Public modules (
- Subsystem facades: When a directory forms a subsystem with a clear caller-facing interface, keep its implementation submodules private and re-export the interface from
mod.rsviapub use self::...;. Import that interface through the subsystem root both inside and outside the subsystem, and import implementation-only details directly from their defining modules within the subsystem. Do not add a facade to a directory that merely groups unrelated modules, and do not forward the same symbol through multiple ancestors or expose duplicate import paths. - Conditional compilation: Attach
#[cfg(...)]attributes atmodboundaries whenever possible instead of repeating identical feature or target gates across individual items inside a file.
//! Binary framing and compression codecs.
use std::io;
use bytes::BytesMut;
use crate::error::Error;
pub mod frame;
mod compress;
pub use self::compress::Codec;
pub use self::compress::Compression;
mod buffer;
mod varint;
#[cfg(test)]
mod tests;Configure rustfmt.toml so import grouping and doc-comment formatting stay deterministic across contributors and tools:
comment_width = 120
format_code_in_doc_comments = true
group_imports = "StdExternalCrate"
imports_granularity = "Item"
wrap_comments = true- Module-header imports by default: Place shared
useimports at the top of the enclosing module rather than repeating identical imports across functions. Keep auselocal to a function, block, ormatcharm when scoping avoids trait method ambiguity (such as bringing an internal trait into scope for one generic helper without colliding with another trait imported across the file), isolates heavy helper-only namespaces (such as CLI styling, table formatting, snippet rendering, or large enum variant globs) to the single function that uses them, or keeps imports inside a#[cfg(...)]or#[test]item instead of scattering extra#[cfg(...)]attributes across top-of-file imports or wrapping a single#[test]in an artificial module. - No inline
crate::orsuper::paths: Never spellcrate::...,super::..., orself::...inline in expressions or type signatures. Always bring intra-crate items into scope viause crate::...(at the module header or in a scoped localuse), avoiduse super::...and privateuse self::...imports so moving files across directories does not break relative paths, and reserveuse super::*;exclusively for#[cfg(test)]and colocated benchmark modules. - External and standard-library inline paths when simpler: Spelling out
std::...,core::..., or<external_crate>::...inline is welcome whenever it reads more simply than adding an import, such as one-off calls (std::env::var,std::panic::catch_unwind), avoiding#[cfg(...)]-gated imports (std::time::Durationinside a#[cfg(test)]helper), or disambiguating colliding names (impl core::error::Error for Error,jiff::Timestampvs.proto::Timestamp, or wrapper fieldsMutex(std::sync::Mutex<T>)). - Meaningful qualification and minimal aliases: Preserve original symbol names with enough module or crate qualification to clarify context and disambiguate common names (
io::Error,fs::read,process::Command,atomic::Ordering), even without a local conflict. Avoid arbitraryuse ... as ...renames because aliases obscure symbol origin and hurt workspace search; resolve collisions through parent-module qualification or external inline paths first, and import method-only traits withuse ...::Trait as _;(at module scope unless local scoping avoids ambiguity or#[cfg]noise).
// Good: module-header qualified imports, scoped local `use`, and simple inline `std::` paths.
use std::fs;
use std::io;
use std::io::Write as _;
use std::ptr;
use std::str;
use crate::codec::Codec;
fn read_magic(path: &str, codec: &Codec, raw: *const u32) -> Result<u32, io::Error> {
let bytes = codec.decode(&fs::read(path)?)?;
let _header = str::from_utf8(&bytes).map_err(io::Error::other)?;
io::sink().write_all(&bytes)?;
// SAFETY: caller guarantees `raw` is valid for a 4-byte unaligned read.
Ok(unsafe { ptr::read_unaligned(raw) })
}
#[test]
fn roundtrip_smoke() {
use crate::codec::Header;
let timeout = std::time::Duration::from_secs(1);
let _ = (Header::default(), timeout);
}// Bad: bare generic names lose context, `super::` is fragile, aliases hurt search,
// `#[cfg]` gates clutter file headers, and `crate::` paths appear inline.
use std::fs::read;
use std::io::Error as IoError;
use std::ptr::read_unaligned;
use std::str::from_utf8;
#[cfg(test)]
use std::time::Duration;
use super::codec::Header;
#[cfg(test)]
use super::codec::Fixture;
fn decode_bytes(bytes: &[u8]) -> Result<Vec<u8>, IoError> {
crate::codec::Codec::decode(bytes)
}Use a three-tier visibility model: private (the default), plain pub, and pub(crate). Avoid pub(super) and pub(in ...).
- Private by default: Keep items private when they are used only within their defining module and its descendants.
- Module-bounded
pub: Let the enclosing module boundary define the visibility ceiling. Inside a module tree hidden behind a private ancestor (mod internal;), use plainpubfor types, fields, and functions shared across modules in that tree rather than repeatingpub(crate). - Targeted
pub(crate): Reservepub(crate)for internal fields, constructors, or helpers that sit inside a public module (pub mod) or on a type publicly re-exported viapub use, where plainpubwould leak them into the public API. - Test encapsulation: Never widen production visibility solely to let another module's tests inspect internal details.
// src/lib.rs
mod session;
pub use self::session::Session;
mod storage; // private subsystem
// src/storage/page.rs (inside private `mod storage`)
pub struct Slot {
pub offset: u64,
pub len: u32,
}
// src/session.rs (`Session` is publicly re-exported at the crate root)
pub struct Session {
id: u64,
}
impl Session {
pub fn id(&self) -> u64 {
self.id
}
// Reachable through public `Session`; restrict crate-internal construction with `pub(crate)`.
pub(crate) fn from_raw(id: u64) -> Self {
Self { id }
}
}- Naming and layout: Name types, fields, and functions by their concrete role, using the shortest name that stays clear. Keep a type and its primary
implblock together, placing public API methods before private helpers. Reservelenandis_emptyfor collection or slice-like views; choose specific names when reporting byte size, capacity, weight, or retained samples. - Constructors and builders: Use
newfor the primary constructor (implementingDefaultwhen a meaningful parameterless value exists, and marking trivial constructorsconst fnwhen practical) andwith_*for alternative required inputs. Introduce a dedicated*Buildertype when construction has multiple optional settings or staged validation rather than proliferating combinatoric constructors. - No leading underscores on fields: Do not prefix struct, union, or enum-variant fields with
_merely to silence unused-field warnings, as leading underscores obscure construction sites and bypass stale-lint checks. Name retained fields after the resource, guard, or marker they hold, and annotate unread ownership fields with#[expect(dead_code, reason = "...")](PhantomDatafields do not triggerdead_codeand need neither_nor an attribute). By contrast,_paramfor unused function parameters andlet _guard = ...;for local RAII drop guards remain idiomatic Rust.
use std::marker::PhantomData;
use std::sync::Arc;
// Good: descriptive field names and explicit ownership intent.
pub struct PooledConn<'a> {
raw: RawConn,
#[expect(dead_code, reason = "retains pool lease until the connection is dropped")]
lease: Arc<Lease>,
marker: PhantomData<&'a ()>,
}
// Bad: leading underscores obscure ownership and bypass stale-lint checks.
pub struct PooledConn<'a> {
raw: RawConn,
_lease: Arc<Lease>,
_marker: PhantomData<&'a ()>,
}- Standard traits: Derive applicable value traits (
Debug,Clone,Copy,PartialEq,Eq,Hash) on plain data types and configuration enums. Deliberately omitPartialEqandEqwhen field-wise equality would reflect internal layout, history, or random seeds rather than a sound domain equality contract. ImplementDebugmanually on custom iterators and view types when#[derive(Debug)]would impose unnecessary generic bounds on type parameters. - Restrained
#[must_use]: Omit routine#[must_use]annotations on ordinary getters, queries, and consuming builder methods. Reserve#[must_use = "..."]with an explicit reason for lazy iterators or futures, RAII guards, non-Resultoutcome or report types whose dismissal silently loses failures or resources, and&selfmethods that callers could mistake for in-place mutators. - Lint baseline and
#[expect]: Prefer#[expect(lint, reason = "...")]over#[allow(lint)]so local suppressions fail once the underlying warning disappears; targeted#[allow(lint)]with an explanatory comment is acceptable only when reachability genuinely varies across feature or toolchain matrices. InCargo.toml, configure workspace lints to catch unknown lints, ignoredmust_usevalues, stray debug macros, and unintendedunsafeusage:
[workspace.lints.rust]
unknown_lints = "deny"
unsafe_code = "deny" # Use `unsafe_op_in_unsafe_fn = "deny"` in crates that require unsafe code
unused_must_use = "deny"
[workspace.lints.clippy]
dbg_macro = "deny"- Linear control flow: Keep abstractions at function signatures, cohesive types, and module boundaries. Inside functions, write direct, top-to-bottom logic using early guard returns and explicit
matchorif letbranches. - Loops vs. combinators: Prefer explicit
forloops for multi-step transformations, stateful accumulation, or fallible validation; use iterator chains for concise, side-effect-free mappings. - Earned complexity: Require every helper, wrapper type, or trait layer to justify its cognitive cost. Small local duplication that keeps branches independent and readable is preferable to premature indirection or defensive glue code without an explicit contract.
- Errors, absence, and panics:
- Return
Result<T, E>for recoverable failures that callers can handle, report, or retry. Keep failing mutations atomic with respect to observableselfstate whenever practical. - Return a natural empty value (
0,false, or an empty collection) orOption<T>for absent query results rather than modeling absence as an error. - Fail fast (
assert!,panic!,unreachable!) on violated internal invariants or unrecoverable programming bugs instead of widening infallible signatures toResultor silently substituting fallback values. - Preserve structured causes and domain context across error boundaries; expose typed fields or accessors when callers need programmatic recovery rather than forcing string inspection on formatted error messages.
- Return
- Observable contracts only: Write
///documentation from the caller's perspective, covering behavior, preconditions, ownership transfers, and state transitions. Keep internal data structures, lock mechanics, trait-coherence workarounds, and historical design rationale out of public API docs. - Voice and formatting: Describe types with noun phrases (
A bounded frame decoder.) and functions or methods with third-person present-tense verbs (Creates,Decodes,Returns). End summary sentences with periods, and wrap Rust identifiers, literals, and numeric ranges in inline code spans. - Clean intra-doc links: Use public API names as intra-doc link labels and hide private module paths in explicit link targets (such as
[`Codec`][crate::compress::Codec]) so internal module layouts do not leak into rendered prose. - Contract sections: Include section headings only when they state an actual contract, ordered before
# Examples:- Explain straightforward return values in the summary or body; add an optional
# Returnssection only for non-trivial outcomes, snapshots, or ownership rules. # Errors: Concrete conditions under which a fallible operation returnsErr.# Panics: Concrete caller-visible panic preconditions.# Safety: Invariants callers must uphold when calling anunsafe fnor implementing anunsafe trait.- Domain-specific contract sections (when a crate defines them) appear before
# Examples. # Examples(optional, always last): Demonstrate realistic behavior rather than mechanical syntax, keepinguseimports visible (a trailing hiddenOk::<(), Error>(())is fine to support?).
- Explain straightforward return values in the summary or body; add an optional
- Inline comments: Prefer self-explanatory code over commentary that restates what the code does. Reserve
//comments for non-obvious invariants, concurrency orunsafepreconditions (// SAFETY: ...), external protocol quirks, or performance rationale that types and names cannot express.
- Contract-first coverage: Exercise observable behavior through public APIs whenever practical; keep
#[cfg(test)]unit tests next to the implementation strictly for non-trivial private invariants or state machines that black-box tests cannot cover cleanly. - High-value tests only: Every test should protect against a plausible bug or boundary regression without inflating maintenance cost. Do not add tests merely because code changed, and remove tests that restate literals, mirror trivial control flow, check static type guarantees, or assert non-contract
Debugor diagnostic wording. - Production purity and determinism: Do not add test-only hooks or complicate production paths to expose internal state. In concurrent tests, coordinate execution deterministically (with channels, barriers, notifications, or controlled clocks) instead of sleeping.
See AGENTS.template.md for a condensed, example-free version ready to copy or adapt into a repository's AGENTS.md alongside project-specific architecture and domain contracts.