typestar

Modules, tests & macros

12 steps in 5 sets of Rust.

What surrounds the code. Modules and visibility, the test attributes and doc tests that make Rust's tooling unusually good, and macro_rules for when a function will not do.

The last set is API design: builders, newtypes, and the patterns that make a crate pleasant to use from outside. Twelve steps, mostly about the difference between code that works and code someone else can depend on.

Start this tour

Modules & visibility

  • ModulesA module tree inside one file: mod declares, pub opens, paths reach in.
  • use, as and re-exportsBringing names into scope, renaming clashes, and re-exporting an API.
  • Visibilitypub(crate) and private fields are how a module keeps its invariants.

Tests & docs

  • Unit testsTests live beside the code in a cfg(test) module, compiled only for test runs.
  • Testing errors and panicsTests can return Result, and should_panic asserts the failure you expect.
  • Doc comments/// documents the item below it, and the example in it is a test that runs.

Macros

  • Derive macrosThe derives worth reaching for, and what each one buys you.
  • macro_rules!A declarative macro matches syntax patterns and expands to code.
  • Macros with repetitionRepetition captures a list, so one macro builds a whole collection.

API patterns

Encore

  • inventory.rsA small module tree with a builder, private invariants and its own tests.

The other Rust tours