Blog

Part 18 · Modules, Crates and Workspaces in Rust

Modules split a Rust program into named parts, and everything in them is private until you write pub. This part covers mod, pub, paths, use, files, library and binary crates, and workspaces.

So far every program in this series has been one file with one main. Real programs grow past that. Rust gives you three tools to split them up: modules to group code inside one crate, crates to build a library or a program, and workspaces to keep several crates together.

This part covers mod and pub, the paths crate::, super:: and self::, use, moving modules into their own files, a package with both src/lib.rs and src/main.rs, and a small workspace. It uses structs from Part 10, traits from Part 14 and trait bounds from Part 15. Every program here was run on Rust 1.95, and its output is pasted from the run. The multi-file project is checked by a script that builds it and compares its output.

Try this first

mod greetings { ... } makes a module called greetings, a named box for code. main then calls the function inside it. Does this compile?

mod greetings {
    fn hello() -> String {
        String::from("hello")
    }
}

fn main() {
    println!("{}", greetings::hello());
}

It doesn’t:

error[E0603]: function `hello` is private
 --> src/main.rs:8:31
  |
8 |     println!("{}", greetings::hello());
  |                               ^^^^^ private function
  |
note: the function `hello` is defined here
 --> src/main.rs:2:5
  |
2 |     fn hello() -> String {
  |     ^^^^^^^^^^^^^^^^^^^^

In Rust, everything inside a module is private unless you say otherwise. main is outside greetings, so it can’t see hello. The fix is one word, pub:

mod greetings {
    pub fn hello() -> String {
        String::from("hello")
    }
}

fn main() {
    println!("{}", greetings::hello());
}

It prints:

hello

Private by default is a choice. You decide what other code may use, and everything else stays yours to change. The rest of this part is about drawing that line.

Packages and crates

Two words come first, because cargo uses both.

  • A crate is what the compiler builds in one go. It’s either a binary crate, a program with a main, or a library crate, code for other crates to use, with no main.
  • A package is a folder with a Cargo.toml. It holds one or more crates.

cargo new hello makes a package with one binary crate, whose root file is src/main.rs. cargo new --lib geometry makes a package with one library crate, whose root is src/lib.rs. A package can have both files at once. Then it has two crates with the same name: a library, and a program that uses it. That’s the shape of the project later in this part.

The crate root is the file the compiler starts from. Every module in the crate hangs off it like a branch off a tree.

Modules inside one file

A module can sit right inside another file, between braces. Modules nest, and a path names an item by walking down the tree with :::

mod zoo {
    pub mod birds {
        pub fn count() -> u32 {
            12
        }
    }

    pub mod cats {
        pub fn count() -> u32 {
            3
        }
    }
}

fn main() {
    let total = zoo::birds::count() + zoo::cats::count();
    println!("birds {}, cats {}", zoo::birds::count(), zoo::cats::count());
    println!("total {total}");
}

It prints:

birds 12, cats 3
total 15

Both modules have a function called count, and that’s fine. zoo::birds::count and zoo::cats::count are different paths, so the names never clash. That’s the first job of a module: a separate space for names.

Notice that zoo itself has no pub, yet main can use it. zoo and main both sit at the crate root, so they’re in the same module, and anything can see its own neighbours. birds and cats do need pub, because main is outside zoo.

The privacy rules

The whole system fits in a few lines:

  • An item is private by default. A private item can be used in the module where it’s defined, and in that module’s children.
  • pub makes it visible wherever its parent module is visible.
  • pub(crate) makes it visible anywhere in the same crate, and nowhere outside it.
  • pub(super) makes it visible in the parent module.

“Children can see their parents’ private items” is the rule people miss. A module’s helpers are private to the outside world, but not to the code nested inside it. Here a child module calls a private function of its parent:

mod kitchen {
    fn boil() -> String {
        String::from("hot water")
    }

    pub mod teapot {
        pub fn brew() -> String {
            format!("tea made with {}", super::boil())
        }
    }
}

fn main() {
    println!("{}", kitchen::teapot::brew());
}

It prints:

tea made with hot water

boil has no pub, and main couldn’t call it. teapot can, because teapot lives inside kitchen. Privacy hides the inside of a module from the outside, not from itself.

Struct fields are private too

pub struct makes the type public. Each field is still private unless it has its own pub. Methods in an impl block work the same way: each one needs pub to be called from outside the module.

Enums are different. A variant can’t have its own privacy, so in a pub enum, every variant is public. A pub enum Direction { Up, Down } would be useless if other code couldn’t name Direction::Up.

Paths: crate::, super:: and self::

A path can start in three places:

  • crate:: starts at the crate root. It’s an absolute path: it means the same thing wherever you write it.
  • super:: starts at the parent module, like .. in a file path.
  • self:: starts at the current module. You rarely need it, because a plain name already means “in this module”.
mod pantry {
    pub fn tea_leaves() -> &'static str {
        "green tea"
    }
}

mod kitchen {
    fn water() -> &'static str {
        "hot water"
    }

    pub fn make_tea() -> String {
        let leaves = crate::pantry::tea_leaves();
        let water = self::water();
        format!("{leaves} in {water}")
    }

    pub mod oven {
        pub fn bake() -> String {
            format!("bread, with {} for steam", super::water())
        }
    }
}

fn main() {
    println!("{}", kitchen::make_tea());
    println!("{}", crate::kitchen::oven::bake());
}

It prints:

green tea in hot water
bread, with hot water for steam

crate::pantry::tea_leaves works from anywhere in the crate. super::water works from oven because water is in its parent. self::water() and plain water() do the same thing here.

Which to choose? Use crate:: when the item is far away. It doesn’t break when you move the module that uses it. Use super:: for an item in the parent module, the way a test module reaches the code it tests (Part 19 shows this).

use: shorter names

Writing crate::kitchen::oven::bake every time gets long. use brings a name into the current module, so you can write the short form:

mod shop {
    pub mod money {
        pub fn cents_to_text(cents: u32) -> String {
            format!("${}.{:02}", cents / 100, cents % 100)
        }
    }
}

use shop::money;

fn main() {
    println!("{}", money::cents_to_text(1999));
    println!("{}", money::cents_to_text(5));
}

It prints:

$19.99
$0.05

use shop::money makes money a short name for shop::money. It doesn’t copy anything or change privacy. It only makes a shortcut. The shortcut belongs to the module where you write it, so a child module needs its own use.

Rust code usually follows two habits. For a function, bring in its module and call money::cents_to_text(..), as above, so a reader can see where the function comes from. For a struct, enum or trait, bring in the item itself, as in use std::collections::HashMap;.

Renaming with as

Sometimes two items have the same name. std::fmt::Result and std::io::Result are both called Result. as gives one of them a local name:

use std::fmt;
use std::fmt::Result as FmtResult;
use std::io::Result as IoResult;
use std::io::Write;

struct Celsius(f64);

impl fmt::Display for Celsius {
    fn fmt(&self, f: &mut fmt::Formatter) -> FmtResult {
        write!(f, "{:.1} C", self.0)
    }
}

fn print_all(temps: &[Celsius]) -> IoResult<()> {
    let mut out = std::io::stdout();
    for t in temps {
        writeln!(out, "{t}")?;
    }
    Ok(())
}

fn main() -> IoResult<()> {
    print_all(&[Celsius(21.5), Celsius(-3.0)])
}

It prints:

21.5 C
-3.0 C

Re-exporting with pub use

A plain use makes a shortcut for the current module only. pub use makes the shortcut part of the module’s public API. Other code can then use the item through the new path, even if its real home is private:

mod library {
    mod internal {
        pub mod deep {
            pub fn answer() -> u32 {
                42
            }
        }
    }

    pub use internal::deep::answer;
}

fn main() {
    println!("{}", library::answer());
}

It prints:

42

Nothing outside library can name library::internal, because internal is private. But library::answer works. This is how a library keeps its files arranged the way that suits its authors, and still gives its users short paths. The standard library does it all the time.

Glob imports, and why to avoid them

use some_module::*; brings in every public name at once. It saves typing, and it hides where names come from. Worse, two globs can bring in the same name:

mod csv {
    pub fn parse(line: &str) -> Vec<&str> {
        line.split(',').collect()
    }
}

mod words {
    pub fn parse(line: &str) -> Vec<&str> {
        line.split_whitespace().collect()
    }
}

use csv::*;
use words::*;

fn main() {
    println!("{:?}", parse("a,b c"));
}

It prints:

error[E0659]: `parse` is ambiguous
  --> src/main.rs:17:22
   |
17 |     println!("{:?}", parse("a,b c"));
   |                      ^^^^^ ambiguous name
   |
   = note: ambiguous because of multiple glob imports of a name in the same module

This one fails at least. The quieter trouble comes later: someone adds a parse to a module you glob-import, and a name in your code suddenly means something else, or stops compiling. Name what you use. Globs are fine in two places: a test module’s use super::*; (Part 19), and a library’s “prelude” module that’s made to be glob-imported.

Modules in their own files

Braces are fine for small modules. A real crate puts each module in its own file. The braces go away, and a line with a semicolon takes their place:

mod shapes;

That line means “there is a module called shapes, and its code is in a file”. The compiler looks for the file next to the one that declared it. If it isn’t there, the error tells you exactly where it looked:

mod shapes;

fn main() {
    shapes::hello();
}

It prints:

error[E0583]: file not found for module `shapes`
 --> src/main.rs:1:1
  |
1 | mod shapes;
  | ^^^^^^^^^^^
  |
  = help: to create the module `shapes`, create file "src/shapes.rs" or "src/shapes/mod.rs"

Two file names work for the same module:

  • src/shapes.rs, the modern layout, used since Rust 2018;
  • src/shapes/mod.rs, the older layout. It still works, and you’ll see it in older code.

A module with children needs a folder for them either way. In the modern layout, src/shapes.rs holds shapes itself, and src/shapes/circle.rs holds shapes::circle. In the old layout, every module with children is a mod.rs, and an editor with five tabs called mod.rs is one reason the new layout won. Pick one style per project. Don’t make both files for one module: the compiler refuses that with E0761, “file for module shapes found at both”.

One more rule: a file is part of the crate only if some mod line names it. The compiler doesn’t scan the src folder. A src/report.rs with no mod report; anywhere is never compiled, and use crate::report fails with E0432, “unresolved import”.

Worked example: one package, a library and a program

Here is a real project, rust/examples/18-modules/ in the series’ repository. The package is called geometry, and it has a library crate and a binary crate:

18-modules/
  Cargo.toml          [package] name = "geometry"
  src/
    lib.rs            crate root of the library
    shapes.rs         mod shapes
    shapes/
      circle.rs       mod shapes::circle
      square.rs       mod shapes::square
    report.rs         mod report
    main.rs           crate root of the program

The library’s root declares the two top-level modules and re-exports the items users need:

//! A tiny geometry library: two shapes, and a report that lists them.

pub mod report;
pub mod shapes;

// Re-exports: users can write `geometry::Circle`
// instead of `geometry::shapes::circle::Circle`.
pub use report::Report;
pub use shapes::Shape;
pub use shapes::circle::Circle;
pub use shapes::square::Square;

A line starting //! is a doc comment for the module it’s in, and /// documents the item below it. cargo doc turns both into web pages, as we’ll see at the end.

src/shapes.rs declares its own two children, a trait, and a helper that every shape uses:

pub mod circle;
pub mod square;

/// Anything with a name and an area.
pub trait Shape {
    fn name(&self) -> String;
    fn area(&self) -> f64;
}

/// Turns a negative size into a positive one. Every shape in this crate
/// uses it, but it isn't part of the public API.
pub(crate) fn non_negative(size: f64) -> f64 {
    size.abs()
}

non_negative is pub(crate). Any module in the library may call it, but it isn’t part of what the library offers. We’ll prove that below.

circle.rs reaches its parent with super::. Its field is private, so the only way to make a Circle is Circle::new, and new makes sure the radius is never negative:

use super::{Shape, non_negative};
use std::f64::consts::PI;

pub struct Circle {
    radius: f64,
}

impl Circle {
    pub fn new(radius: f64) -> Circle {
        Circle {
            radius: non_negative(radius),
        }
    }

    pub fn radius(&self) -> f64 {
        self.radius
    }
}

square.rs uses an absolute path to reach the same two items, just to show the other way. Its field is pub, which matters in a moment:

use crate::shapes::{Shape, non_negative};

pub struct Square {
    pub side: f64,
}

report.rs builds a small table. Its fields and its row helper are private, and add takes any type that implements Shape:

use crate::shapes::Shape;

pub struct Report {
    title: String,
    rows: Vec<(String, f64)>,
}

impl Report {
    pub fn new(title: &str) -> Report {
        Report {
            title: title.to_string(),
            rows: Vec::new(),
        }
    }

    pub fn add<S: Shape>(&mut self, shape: &S) {
        self.rows.push((shape.name(), shape.area()));
    }

    pub fn render(&self) -> String {
        let mut out = format!("{}\n", self.title);
        for (name, area) in &self.rows {
            out.push_str(&row(name, *area));
        }
        let total: f64 = self.rows.iter().map(|(_, area)| area).sum();
        out.push_str(&row("total", total));
        out
    }
}

// Private: only code in this module can call it.
fn row(label: &str, area: f64) -> String {
    format!("  {label:<12}{area:>8.2}\n")
}

Finally, src/main.rs. It’s a separate crate, and it uses the library by the package name, geometry, the same way it would use a crate downloaded from crates.io:

use geometry::{Circle, Report, Shape, Square};

fn main() {
    let c = Circle::new(-1.5);
    println!("{} has radius {}", c.name(), c.radius());

    let mut s = Square::new(2.0);
    s.side = -3.0;
    println!("{} has area {}", s.name(), s.area());

    let mut report = Report::new("Areas");
    report.add(&c);
    report.add(&Square::new(2.0));
    report.add(&s);
    print!("{}", report.render());
}

cargo run prints:

circle r=1.5 has radius 1.5
square s=-3 has area 9
Areas
  circle r=1.5    7.07
  square s=2      4.00
  square s=-3     9.00
  total          20.07

Look at the two shapes. Circle::new(-1.5) gave a radius of 1.5, and there’s no way around that: main can’t touch radius. Square::new(2.0) was fine too, but side is public, so main set it to -3.0 and the library never noticed. A private field lets the type keep a promise. A public field hands the promise to every user. (The area is still 9, but a square with a side of -3 is a bug waiting for somebody’s code.)

main.rs also needs use geometry::Shape, even though it never writes the word Shape in its body. name and area are trait methods, and Rust lets you call a trait’s methods only where the trait itself is in scope. Part 14 never hit this, because each trait was defined in the same file that used it.

Here is the module tree of that package, with what each part can see:

pub pub(crate) private crate root: geometry src/lib.rs, with four pub use lines mod shapes src/shapes.rs non_negative trait Shape mod circle src/shapes/circle.rs pub struct Circle radius: f64 new(), radius() mod square src/shapes/square.rs pub struct Square pub side: f64 new() mod report src/report.rs pub struct Report title, rows fn row super:: crate:: crate:: From src/main.rs, a separate crate that uses geometry: yes geometry::Circle::new(-1.5) pub, and re-exported at the root yes s.side = -3.0 a pub field E0616 c.radius a private field of Circle E0603 geometry::shapes::non_negative(-1.0) pub(crate): only inside geometry

The geometry library’s module tree. Blue arrows are paths that work inside the crate. From main.rs, a separate crate, only the pub items are reachable.

In words, from the top:

  1. The crate root, src/lib.rs, declares shapes and report, and re-exports four items so users get short paths.
  2. shapes holds the public trait Shape and the pub(crate) helper non_negative. Its child circle imports Shape and the helper with super::, and square imports the same two with crate::. The figure draws one arrow for each.
  3. report reaches Shape with crate::shapes::Shape. Its fields and its row helper are private.
  4. main.rs is another crate. It can use what’s pub all the way down, but not the private field radius, and not the pub(crate) helper.

main.rs is another crate

The last line of that panel is the one that surprises people. non_negative is visible to every module in geometry. It feels like main.rs is part of the same project, so it should see it too. It isn’t. main.rs is the root of a different crate, and to the compiler it’s just another user of the library. The project’s check script compiles this file as its own crate against the library:

fn main() {
    println!("{}", geometry::shapes::non_negative(-1.0));
}

It prints:

error[E0603]: function `non_negative` is private
  --> checks/peek.rs:4:38
   |
 4 |     println!("{}", geometry::shapes::non_negative(-1.0));
   |                                      ^^^^^^^^^^^^ private function

The same line in src/main.rs gives the same error. That’s useful: main.rs can only use the library through its public API, so the API gets tested every time you run the program.

The usual reason to split a package this way is that the library can be tested and reused on its own, and main.rs stays a thin layer that reads input and prints output. A package name with a hyphen, like my-geometry, is written with an underscore in code: use my_geometry::Circle;.

Worked example: a private field keeps a promise

Here’s a bank account whose balance should only change through deposit, which refuses amounts below one cent. The struct is pub and owner is pub, but balance isn’t. Other code tries to read it directly:

mod bank {
    pub struct Account {
        pub owner: String,
        balance: u64,
    }

    impl Account {
        pub fn open(owner: &str) -> Account {
            Account {
                owner: owner.to_string(),
                balance: 0,
            }
        }

        pub fn deposit(&mut self, cents: u64) -> bool {
            if cents == 0 {
                return false;
            }
            self.balance += cents;
            true
        }

        pub fn balance(&self) -> u64 {
            self.balance
        }
    }
}

fn main() {
    let mut acc = bank::Account::open("Ana");
    acc.deposit(500);
    println!("{} has {}", acc.owner, acc.balance);
}

It prints:

error[E0616]: field `balance` of struct `Account` is private
  --> src/main.rs:32:42
   |
32 |     println!("{} has {}", acc.owner, acc.balance);
   |                                          ^^^^^^^ private field

The error points at acc.balance, the field. acc.owner on the same line is fine, because owner is pub. The method balance() is public too. Rust lets a field and a method share a name, and calling the method is how other code reads the value:

mod bank {
    pub struct Account {
        pub owner: String,
        balance: u64,
    }

    impl Account {
        pub fn open(owner: &str) -> Account {
            Account {
                owner: owner.to_string(),
                balance: 0,
            }
        }

        pub fn deposit(&mut self, cents: u64) -> bool {
            if cents == 0 {
                return false;
            }
            self.balance += cents;
            true
        }

        pub fn balance(&self) -> u64 {
            self.balance
        }
    }
}

fn main() {
    let mut acc = bank::Account::open("Ana");
    println!("deposit 500: {}", acc.deposit(500));
    println!("deposit 0: {}", acc.deposit(0));
    println!("{} has {} cents", acc.owner, acc.balance());
}

It prints:

deposit 500: true
deposit 0: false
Ana has 500 cents

A private field also blocks the other way in. Code outside bank can’t build an Account with a struct literal, because it would have to name balance:

mod bank {
    pub struct Account {
        pub owner: String,
        balance: u64,
    }

    impl Account {
        pub fn balance(&self) -> u64 {
            self.balance
        }
    }
}

fn main() {
    let acc = bank::Account {
        owner: String::from("Eve"),
        balance: 1_000_000,
    };
    println!("{}", acc.balance());
}

It prints:

error[E0451]: field `balance` of struct `Account` is private

So one private field forces every Account to be made by open and changed by deposit. Later you can add a log of deposits, or a limit, and no code outside bank has to change, because none of it ever touched balance. That’s the practical reason to keep fields private: the module can change its insides freely.

Worked example: a workspace with two packages

A package has at most one library crate. When a project grows into several libraries, or several programs that share one, you put the packages in a workspace. A workspace is a folder whose Cargo.toml lists its member packages. The members share one Cargo.lock and one target folder, so a crate they all use is built once.

The example project has a small one in 18-modules/workspace/:

workspace/
  Cargo.toml          [workspace] members = ["temperature", "thermo"]
  temperature/        a library package
    Cargo.toml
    src/lib.rs
  thermo/             a binary package that uses it
    Cargo.toml
    src/main.rs

The top-level Cargo.toml has no [package] at all, only the list:

[workspace]
members = ["temperature", "thermo"]
resolver = "3"

resolver = "3" picks the newest way cargo chooses dependency versions. A package with edition 2024 gets it by default, but a workspace with no root package has no edition of its own. Leave the line out, and cargo warns that it’s falling back to the old resolver 1.

thermo depends on its neighbour by path, in thermo/Cargo.toml:

[dependencies]
temperature = { path = "../temperature" }

and uses it exactly like the geometry library above:

use temperature::{to_celsius, to_fahrenheit};

fn main() {
    for c in [-40.0, 0.0, 37.0, 100.0] {
        println!("{c:>6.1} C = {:>6.1} F", to_fahrenheit(c));
    }
    println!("{:.1} C", to_celsius(98.6));
}

From the workspace folder, these are the commands you’ll use:

cargo build                 build every member
cargo run -p thermo         run one member's program
cargo test -p temperature   test one member
cargo clippy --workspace    lint every member

cargo run -p thermo prints:

 -40.0 C =  -40.0 F
   0.0 C =   32.0 F
  37.0 C =   98.6 F
 100.0 C =  212.0 F
37.0 C

Inside thermo, temperature is just another crate. Only its pub items are visible, the same as geometry from its main.rs. A workspace changes how things are built, not the privacy rules.

cargo doc

cargo doc --open builds web pages for your crate from its //! and /// comments and opens them in a browser. It’s also a quick check of what your public API is, because it shows only public items. For geometry, the pages list Circle, Square, Shape and Report, and the crate’s front page has a “Re-exports” section with the four pub use lines. non_negative isn’t there, because it’s pub(crate). The check script confirms both. Every crate on crates.io gets the same kind of pages at docs.rs.

Tips and traps

  • A new file that “isn’t found”. You made src/report.rs, and use crate::report fails with E0432. A file joins the crate only through a mod report; line in its parent. Add it to lib.rs or main.rs, or to the parent module’s file.
  • mod twice for one file. mod shapes; belongs in exactly one place, the parent. Other modules reach it with use crate::shapes. Writing mod shapes; again in another file makes the compiler look for a second, nested file, and fails with E0583.
  • pub struct with private fields. The type is public but nobody outside can build it with a literal (E0451) or read a field (E0616). That’s often what you want. If it isn’t, add pub to the fields, or give the struct a pub fn new.
  • Forgetting pub on the module itself. pub fn inside a private mod is still hidden from other crates, because the path to it goes through the private module. Make the module pub, or re-export the item with pub use.
  • Trait methods “not found”. Leave Shape out of the use line in main.rs, and c.name() fails with E0599, “no method named name found for struct Circle“, though Circle implements Shape. Bring the trait into scope with use geometry::Shape;. The compiler’s help: line says the trait isn’t in scope.
  • Glob imports in ordinary code. use a::*; hides where a name came from, and a later change in a can break or quietly change your code. List the names instead.

Everything is private until you write pub, so each module decides what the rest of the code may use.

Exercises

Exercise 1. This program doesn’t compile. Make it print today: raking leaves by adding pub in as few places as possible. Which item can stay private, and why?

mod garden {
    mod tools {
        fn rake() -> &'static str {
            "raking leaves"
        }
    }

    fn work() -> String {
        format!("today: {}", tools::rake())
    }
}

fn main() {
    println!("{}", garden::work());
}

It prints:

error[E0603]: function `rake` is private
...
error[E0603]: function `work` is private

Exercise 2. Fill in the body of summary twice: once with a path that starts with super::, and once with a path that starts with crate::. It should return area 12.

mod shapes {
    pub fn area(w: u32, h: u32) -> u32 {
        w * h
    }

    pub mod report {
        pub fn summary() -> String {
            // call area(3, 4) here
        }
    }
}

Exercise 3. A shop keeps its Price type in a private module. Without making money public, make use shop::Price; work in main:

mod shop {
    mod money {
        pub struct Price(pub u32);
    }
}

use shop::money::Price;

fn main() {
    let p = Price(250);
    println!("{} cents", p.0);
}

It prints:

error[E0603]: module `money` is private
Answers

1. Two items need pub: rake, because garden is outside tools, and work, because main is outside garden. The module tools can stay private. Only garden uses it, and garden is its parent, so it can always see it.

mod garden {
    mod tools {
        pub fn rake() -> &'static str {
            "raking leaves"
        }
    }

    pub fn work() -> String {
        format!("today: {}", tools::rake())
    }
}

fn main() {
    println!("{}", garden::work());
}

It prints:

today: raking leaves

2. report is a child of shapes, so super::area names the function in the parent. crate::shapes::area starts at the root and works from anywhere. Both are shown here:

mod shapes {
    pub fn area(w: u32, h: u32) -> u32 {
        w * h
    }

    pub mod report {
        pub fn summary() -> String {
            format!("area {}", super::area(3, 4))
        }

        pub fn summary_absolute() -> String {
            format!("area {}", crate::shapes::area(3, 4))
        }
    }
}

fn main() {
    println!("{}", shapes::report::summary());
    println!("{}", shapes::report::summary_absolute());
}

It prints:

area 12
area 12

3. Re-export it with pub use. money stays private, but shop::Price is now a public path to the same type:

mod shop {
    mod money {
        pub struct Price(pub u32);
    }

    pub use money::Price;
}

use shop::Price;

fn main() {
    let p = Price(250);
    println!("{} cents", p.0);
}

It prints:

250 cents

What’s next

The geometry library has no tests yet, and its layout is the reason it’s easy to add them. In Part 19, we’ll write unit tests next to the code, integration tests in a tests/ folder that see only the public API, and doc tests inside those /// comments.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.