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
http://crates.io 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/lib.rs
is a librarysrc/main.rs
is a binarysrc/mod.rs
is a module top-level for a library
You can override all of this in
Cargo.toml
Cargo Fetches Crates
The
[dependencies]
section ofCargo.toml
allows specifying other crates used by this crateThis is by far the sanest way to do separate compilation
Can specify
crates.io
crates:foo = "0.4.*"
- Github crates:
foo = { git = "http://github.com/something/foo.git" }
- Local crates: `foo = { path = "/local/src/foo" }
Must say `extern crate foo
Namespaces
Using a library
- Rust 2015 edition: need to say
extern crate foo;
at the top of your file to use a crate - Rust 2018 edition: nope
- Rust 2015 edition: need to say
Namespaces are
::
separated as in some other languagesstd::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
Most of this machinery, but not all, is available in any scope
Modules In Separate Files
In addition to explicit
mod { ... }
declarations, can make a filefoo.rs
a module by sayingmod foo;
at the top of its parent module.The filename is inferred from the module name, so be careful.
You can also make a directory contain a module and its submodules by putting a
mod.rs
at the root of the directory.
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 visibleFor 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
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
Fairly complicated module structure
Binary with libraries