Crates and Modules

Rust Has A Module System

  • Better than most, not as good as SML
  • Name-based, but with inter-module typechecking
  • Two kinds of thing
    • "Crates": self-contained packages
    • "Modules": namespaces within a package
  • is the big repository of published crates

Library and Binary Crates

  • A crate can correspond to a program that can be installed
  • A crate can correspond to a library that can be published
  • By default, directory structure gives Cargo what it needs
    • src/ is a library
    • src/ is a binary
    • src/ is a module top-level for a library
  • You can override all of this in Cargo.toml

Cargo Fetches Crates

  • The [dependencies] section of Cargo.toml allows specifying other crates used by this crate
  • This is by far the sanest way to do separate compilation
  • Can specify
    • crates: foo = "0.4.*"
    • Github crates: foo = { git = "" }
    • Local crates: `foo = { path = "/local/src/foo" }
  • Must say `extern crate foo


  • Need to say extern crate foo; at the top of your file to use a crate
  • Namespaces are :: separated as in some other languages
    • std::io::stdin()
    • use std::io::stdin; stdin(); io::stdin()
  • The mod directive introduces a new namespace in the current spot
    • Can make a block a module
    • Can make a file a module with a bare mod directive at top
  • Most of this machinery, but not all, is available in any scope

Making Things pub

  • By default, nothing in a module is visible outside the module/crate in which it is declared
  • You can put pub in front of an item to make it externally visible
  • For things like structs and enums, the visibility of the thing and its fields is controlled separately
  • The compiler will whine at you about an unused thing unless it is pub, in which case it assumes you just know

A Note About Rustup

  • Manages various compiler versions
  • Easiest way to make everything current / sane

Semantic Versioning

  • Three-part version numbers: breaking.major.minor
  • Supposedly improves stability
  • Cargo.lock preserves versioning

Docs and Testing

  • Doc comments have an extra slash
  • Mostly usable with libraries
  • Formatted with Markdown
  • Doc comments
  • Tests and the #[test] and #[cfg(test)] and stuff

An Example: woodpieces

Last modified: Thursday, 19 April 2018, 6:31 PM