Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 7 · Modules & crates

    7.1Modules, visibility & paths

    How Rust groups code into a tree of modules, why everything is private until you mark it pub, and how use, crate::, super:: and self:: find things.

    About 25 minutesBeginner

    On this page
    1. Concept map
    2. Declaring a module
    3. Modules live in files
    4. Private by default
    5. Struct fields are private too
    6. The visibility levels
    7. Paths: crate::, super:: and self::
    8. use creates a shortcut
    9. Re-exports with pub use
    10. Which one should I use?
    11. Under the hood
    12. Common pitfalls
    13. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Unit of code organizationA file; every file is an ES moduleA namespace, independent of files and foldersA module: mod name { … } inline, or mod name; for a file
    Default visibilityPrivate to the file until you export itprivate for members, internal for top-level typesPrivate to the module and the modules inside it
    Visible everywhereexportpublicpub
    Visible only inside this packageExported, but left out of the package's exports mapinternalpub(crate)
    Bringing a name into scopeimport { total } from "./cart.js"using Shop.Cart;use crate::shop::cart::total;
    Re-exportingexport { total } from "./cart.js"No equivalent; a type's name is fixed by its namespacepub use cart::total;

    In TypeScript, every file is a module: what you export is public, everything else is private to the file, and import pulls names in by file path.In C#, a namespace is a name prefix that any file can add to, and access modifiers (public, internal, private, protected) on each type and member decide who can use it. Rust uses modules: named scopes, nested into one tree per crate. You declare every module with mod, everything in it is private until you mark it pub, and paths such as crate::shop::cart::total find things in the tree.

    Declaring a module

    The same small pricing module, with one public function and one private constant:

    TypeScript
    pricing.ts
    const TAX_PERCENT = 20; // not exported: private to this file
    
    export function priceWithTax(cents: number): number {
      return cents + (cents * TAX_PERCENT) / 100;
    }
    
    console.log(priceWithTax(1000));
    C#
    Pricing.cs
    using Shop.Pricing;
    
    Console.WriteLine(Prices.PriceWithTax(1000));
    
    namespace Shop.Pricing
    {
        public static class Prices
        {
            private const int TaxPercent = 20;
    
            public static int PriceWithTax(int cents) => cents + cents * TaxPercent / 100;
        }
    }
    Rust
    mod pricing {
        const TAX_PERCENT: u32 = 20; // private: only this module can use it
    
        pub fn price_with_tax(cents: u32) -> u32 {
            cents + cents * TAX_PERCENT / 100
        }
    }
    
    fn main() {
        println!("{}", pricing::price_with_tax(1000));
    }

    Output

    1200

    mod pricing { … } creates a module named pricing. pub makes price_with_tax visible outside it; TAX_PERCENT has no pub, so only code inside pricing can use it. Outside, you name the function by its path: pricing::price_with_tax. :: separates the parts of a path (modules, types, associated functions), and . is for fields and methods of a value, as Reading Rust’s symbols explains.

    In TypeScript, one file is one module. In Rust, one file can hold several inline modules, as here, or a module can have a file of its own.
    Unlike a C# namespace, a module can hold functions and constants directly, with no static class around them. Visibility belongs to the module, not the class.

    Real projects put most modules in their own files, which the next section shows. The examples in this lesson use inline mod blocks so each one is a single program you can run; the code is the same when you split it into files.

    Modules live in files

    Here’s a crate with three modules, laid out the usual way:

    src/
    ├── main.rs        the crate root: declares  mod pricing;  and  mod shop;
    ├── pricing.rs     the body of the pricing module
    ├── shop.rs        the body of the shop module: declares  pub mod cart;
    └── shop/
        └── cart.rs    the body of the shop::cart module
    
    • mod pricing; (a semicolon instead of a body) in main.rs tells the compiler: the body of pricing is in src/pricing.rs. That file holds exactly what you’d write between the braces, with no mod pricing line in it.
    • A module’s children go in a folder named after it. pub mod cart; in src/shop.rs loads src/shop/cart.rs.
    • The older layout puts the parent’s body in src/shop/mod.rs instead of src/shop.rs. It still works and you’ll see it in older code, but don’t use both for one module: that’s error E0761.
    • The compiler starts at the crate root (main.rs or lib.rs) and follows the mod declarations. A file that no mod declares isn’t compiled at all.

    This is the biggest difference from TypeScript. There, a file is a module because it exists, and import "./pricing.js" from any file loads it. In Rust, mod pricing; declares the module once, in its parent. Every other file refers to it by path with use, which only creates a shortcut to a name. mod is not import.

    This is the biggest difference from C#. There, the SDK compiles every .cs file under the project folder, and a file’s namespace has nothing to do with where it is. In Rust, the module tree is the file tree, and each module is declared once, by its parent, with mod.

    The three files above compile to the same thing as this single file. The paths are identical either way, so main calls shop::cart::total in both:

    mod pricing {
        pub fn price_with_tax(cents: u32) -> u32 {
            cents + cents / 5
        }
    }
    
    mod shop {
        pub mod cart {
            pub fn total(prices: &[u32]) -> u32 {
                prices
                    .iter()
                    .copied()
                    .map(crate::pricing::price_with_tax)
                    .sum()
            }
        }
    }
    
    fn main() {
        println!("{}", shop::cart::total(&[1000, 500]));
    }

    Output

    1800

    Private by default

    An item without pub is visible in the module that defines it and in the modules nested inside that one. Nowhere else. Calling a private function from outside its module doesn’t compile:

    mod pricing {
        fn tax(cents: u32) -> u32 {
            cents / 5
        }
    
        pub fn price_with_tax(cents: u32) -> u32 {
            cents + tax(cents)
        }
    }
    
    fn main() {
        println!("{}", pricing::tax(1000));
    }

    Rust doesn't compile this: error E0603

    error[E0603]: function `tax` is private
      --> main.rs:12:29
       |
    12 |     println!("{}", pricing::tax(1000));
       |                             ^^^ private function
       |
    note: the function `tax` is defined here
      --> main.rs:2:5
       |
     2 |     fn tax(cents: u32) -> u32 {
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^

    Struct fields are private too

    pub struct makes the type public, not its fields. Each field needs its own pub. This is how you protect an invariant: callers read the balance through a method and can only change it through deposit.

    TypeScript
    account.ts
    class Account {
      readonly owner: string;
      #balance = 0;
    
      constructor(owner: string) {
        this.owner = owner;
      }
    
      deposit(cents: number): void {
        this.#balance += cents;
      }
    
      get balance(): number {
        return this.#balance;
      }
    }
    
    const account = new Account("Ada");
    account.deposit(500);
    console.log(`${account.owner}: ${account.balance}`);
    C#
    Account.cs
    var account = new Account("Ada");
    account.Deposit(500);
    Console.WriteLine($"{account.Owner}: {account.Balance}");
    
    public class Account(string owner)
    {
        private int balance;
    
        public string Owner { get; } = owner;
        public int Balance => balance;
    
        public void Deposit(int cents) => balance += cents;
    }
    Rust
    mod bank {
        pub struct Account {
            pub owner: String,
            balance: u32, // private: only code in `bank` can read or set it
        }
    
        impl Account {
            pub fn new(owner: &str) -> Self {
                Account {
                    owner: owner.to_string(),
                    balance: 0,
                }
            }
    
            pub fn deposit(&mut self, cents: u32) {
                self.balance += cents;
            }
    
            pub fn balance(&self) -> u32 {
                self.balance
            }
        }
    }
    
    fn main() {
        let mut account = bank::Account::new("Ada");
        account.deposit(500);
        println!("{}: {}", account.owner, account.balance());
    }

    Output

    Ada: 500

    Reading the private field from main is a compile error:

    fn main() {
        let account = bank::Account::new("Ada");
        println!("{}", account.balance);
    }

    Rust doesn't compile this: error E0616

    error[E0616]: field `balance` of struct `Account` is private
      --> main.rs:3:28
       |
     3 |     println!("{}", account.balance);
       |                            ^^^^^^^ private field

    A field and a method can share a name, as balance does here: account.balance is the field and account.balance() calls the method. Rust code uses this for getters, since there are no properties.

    Mental model shiftPrivate means 'this module', not 'this type'

    A #private field in TypeScript belongs to the class: only the class’s own methods can touch it.A private field in C# belongs to the type: only the type’s own members, and types nested inside it, can touch it. In Rust, privacy belongs to the module. Any function in bank, inside an impl or not, can read balance, and so can any module nested inside bank. Outside bank, nothing can. If you want a tighter boundary around a type, give it a module of its own.

    The visibility levels

    RustWho can use itClosest in TypeScriptC#
    (no modifier)The module it’s in, and every module inside that one.Not exported from the file.private, but scoped to the module instead of the type.
    pub(super)The parent module too, and everything inside the parent.No equivalent.
    pub(crate)Any code in the same crate.Exported, but left out of the package’s exports map, so other packages can’t import it.internal.
    pubAny code that can reach it, including other crates when every module on the path is pub too.Exported, and reachable through the package’s exports.public.
    pub(in crate::shop)Everything inside the named ancestor module. Rare.No equivalent.

    There’s no protected, because Rust has no inheritance. Shared behavior comes from traits, which Traits covers.

    Here pub(super) and pub(crate) are both at work. shop is cart’s parent, so it can call subtotal; main isn’t, so it can only call item_count:

    mod shop {
        pub mod cart {
            pub(super) fn subtotal(prices: &[u32]) -> u32 {
                prices.iter().sum()
            }
    
            pub(crate) fn item_count(prices: &[u32]) -> usize {
                prices.len()
            }
        }
    
        pub fn summary(prices: &[u32]) -> String {
            let count = cart::item_count(prices);
            format!("{count} items, {} cents", cart::subtotal(prices))
        }
    }
    
    fn main() {
        let prices = [1000, 500];
        println!("{}", shop::summary(&prices));
        println!("{}", shop::cart::item_count(&prices));
    }

    Output

    2 items, 1500 cents
    2

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

    A path names an item by walking the module tree, like a file path walks folders:

    PathStarts fromLike
    crate::pricing::price_with_taxThe crate root (main.rs or lib.rs).An absolute import from the project root, such as @/pricing with a paths alias.A fully qualified name, such as Shop.Pricing.Prices.
    super::SHIPPINGThe parent module.../ in an import.A name from an enclosing namespace.
    self::cart::total or cart::totalThe current module../ in an import.A name in the current namespace.
    std::collections::HashMapAnother crate: the standard library or a dependency.A package import, such as from "zod".A type from another assembly, such as System.Collections.Generic.

    All three kinds in one program. cart uses an absolute path to reach pricing and a super:: path to reach its parent’s constant:

    mod pricing {
        pub fn price_with_tax(cents: u32) -> u32 {
            cents + cents / 5
        }
    }
    
    mod shop {
        const SHIPPING: u32 = 499; // private, but modules inside `shop` can see it
    
        pub mod cart {
            use crate::pricing::price_with_tax;
    
            pub fn total(prices: &[u32]) -> u32 {
                let goods: u32 = prices.iter().copied().map(price_with_tax).sum();
                goods + super::SHIPPING
            }
        }
    
        pub fn checkout(prices: &[u32]) -> String {
            format!("Total: {} cents", self::cart::total(prices))
        }
    }
    
    use shop::checkout;
    
    fn main() {
        println!("{}", checkout(&[1000, 500]));
    }

    Output

    Total: 2299 cents

    use creates a shortcut

    use brings a name into the current module’s scope, so you can write price_with_tax instead of crate::pricing::price_with_tax. It doesn’t load or run anything. The forms you’ll see:

    use crate::shop::*; // every name in `shop` you can see (use sparingly)
    use std::collections::HashMap; // one item
    use std::fmt::{self, Display}; // the module itself, and an item from it
    use std::io::Result as IoResult; // a new name, to avoid a clash

    Idiomatic RustImport functions by their module, types by name

    The usual style is use std::collections::HashMap; and then HashMap::new() for types and traits, but use std::fs; and then fs::read_to_string(…) for functions. The module prefix shows where a function comes from at every call. Avoid * outside tests and preludes: it hides where names come from.

    An import covers its whole file. A use covers only its module: an inline mod block in the same file doesn’t see the file’s use lines.A using directive covers a whole file (or, with global using, the whole project). A use covers only its module: an inline mod block doesn’t see the use lines of the code around it. The pitfalls section shows the error.

    Re-exports with pub use

    pub use makes a name available at a second path. The usual reason: a library keeps its files organized however it likes, and gives callers short, stable paths.

    mod shop {
        mod cart {
            pub fn total(prices: &[u32]) -> u32 {
                prices.iter().sum()
            }
        }
    
        pub use cart::total;
    }
    
    fn main() {
        println!("{}", shop::total(&[1000, 500]));
    }

    Output

    1500

    cart itself is private, so shop::cart::total doesn’t work from main, even though total is pub. An item is reachable only if every module on its path is visible to you. The pub use gives main another way in: shop::total.

    This is a barrel file: export { total } from "./cart.js"; in an index.ts.
    C# has nothing like it: a type’s full name is fixed by the namespace it’s declared in. With pub use, a Rust library chooses its public paths separately from its file layout, so it can move files without breaking callers.

    Which one should I use?

    Every item gets a visibility, and every module a place in the tree. Pick the narrowest visibility that works; widening it later is easy, while narrowing it can break code that depends on it.

    WhatWhenWhyHow
    Private (no modifier)The default: helpers, constants and fields that only this module uses.You can change or delete it without breaking anything outside the module. Tests in a nested mod tests can still reach it.fn tax(…), balance: u32.
    pub(super)A helper in a child module that only its parent calls.Says “this is for my parent”, and the compiler keeps the rest of the crate out.pub(super) fn subtotal(…).
    pub(crate)Code shared across a library crate that isn’t part of its public API.Other crates can’t depend on it, so changing it never breaks them.pub(crate) fn item_count(…).
    pubThe module’s interface: what other modules, and in a library other crates, call.Each pub item is a promise to callers.pub fn, pub struct, and pub on each field callers may read or set.
    pub useA library wants a shorter or more stable public path than its file layout.Callers write shop::total; you can move the code without breaking them.pub use cart::total; in the parent, often in lib.rs.
    mod name; in its own fileAny module longer than a few lines.One module per file keeps the module tree and the file tree the same.mod pricing; in the parent, code in pricing.rs. Inline mod tests { … } is the common exception.
    Which visibility?
    1. Is it part of your library's API, for other crates to use?

      Yes

      pub, on a path of pub modules or re-exported with pub useFields too: mark each one pub only if callers may read and set it freely.

      No
    2. Does only the parent module need it?

      Yes

      pub(super)

      No
    3. Do other modules in this crate need it?

      Yes

      pub(crate)In a binary crate, plain pub means the same, because no other crate can use a binary.

      No
    4. Otherwise: Leave it private. The module and every module inside it, such as mod tests, can still use it.

    Rule of thumb: start private and add pub when another module needs the item. Keep struct fields private and expose methods, unless the struct is plain data with no rules to protect. In a library, use pub(crate) for anything shared inside the crate, so pub marks exactly the public API.

    Under the hood

    The three-file layout from earlier, as the compiler sees it. Every module hangs off the crate root, and every item has one full path:

    crate                          src/main.rs
    ├── pricing                    src/pricing.rs
    │   └── price_with_tax         pub
    └── shop                       src/shop.rs
        ├── SHIPPING               private: visible in shop and shop::cart
        ├── checkout               pub
        └── cart                   src/shop/cart.rs
            └── total              pub
    

    Modules exist only at compile time:

    • No loading and no top-level code. A module holds items (functions, types, constants, statics, use lines and other modules), never statements to run. An ES module runs its top-level code the first time something imports it, so import order can matter. Nothing like that happens in Rust: there’s no module to load or initialize.Like a namespace, a module has no run-time presence: no static constructor and no initialization order to worry about.
    • No cost at the boundary. The whole crate is compiled as one unit, so a call into another module is an ordinary call, and the compiler can inline it.
    • Privacy is final. The compiler checks it, and there’s no reflection to get around it. TypeScript’s private keyword is erased at compile time, so any code can still read the field at run time; only #private fields are enforced, by the engine.In C#, reflection can read private fields, and [InternalsVisibleTo] opens internal members to a test project.

    Rust tests need neither trick. Unit tests live in a tests module inside the module they test, so they’re a child and can see its private items:

    fn tax(cents: u32) -> u32 {
        cents / 5
    }
    
    pub fn price_with_tax(cents: u32) -> u32 {
        cents + tax(cents)
    }
    
    #[cfg(test)]
    mod tests {
        use super::*; // a child module: it can use private items like `tax`
    
        #[test]
        fn tax_is_a_fifth() {
            assert_eq!(tax(1000), 200);
        }
    }

    #[cfg(test)] compiles the module only for cargo test. The next lesson covers cfg, and Module 13 covers tests.

    Common pitfalls

    Common pitfallA new file does nothing until you declare it

    Creating src/pricing.rs isn’t enough. Until the parent says mod pricing;, the compiler never reads the file, and paths into it fail to resolve. rust-analyzer marks such a file as not included in the module tree. Add the mod line to the parent (main.rs, lib.rs or the parent module’s file).

    Common pitfallmod declares, use refers

    Write mod pricing; exactly once, in the parent. Everywhere else, refer to it with a path: use crate::pricing;. Writing mod pricing; in src/shop.rs doesn’t import the existing module: it declares a new module shop::pricing and makes the compiler look for src/shop/pricing.rs.

    Common pitfalluse lines don't reach into nested modules

    Each module has its own scope. An inline module doesn’t see the use lines around it:

    use std::collections::HashMap;
    
    mod cache {
        pub fn empty() -> HashMap<String, u32> {
            HashMap::new()
        }
    }
    
    fn main() {
        println!("{}", cache::empty().len());
    }

    Rust doesn't compile this: error E0412

    error[E0412]: cannot find type `HashMap` in this scope
     --> main.rs:4:23
      |
    4 |     pub fn empty() -> HashMap<String, u32> {
      |                       ^^^^^^^ not found in this scope
      |
    help: consider importing one of these structs
      |
    4 +     use crate::HashMap;
      |
    4 +     use std::collections::HashMap;
      |
    
    error[E0433]: failed to resolve: use of undeclared type `HashMap`
     --> main.rs:5:9
      |
    5 |         HashMap::new()
      |         ^^^^^^^ use of undeclared type `HashMap`
      |
    help: consider importing one of these structs
      |
    4 +     use crate::HashMap;
      |
    4 +     use std::collections::HashMap;
      |

    Add use std::collections::HashMap; inside cache, or use super::*; to bring in every name from the parent, including its use imports. That’s why every mod tests starts with use super::*;.

    Common pitfallOne private field locks the struct literal

    If a struct has even one private field, code outside its module can’t build it with Account { … }:

    mod bank {
        pub struct Account {
            pub owner: String,
            balance: u32,
        }
    }
    
    fn main() {
        let account = bank::Account {
            owner: String::from("Ada"),
            balance: 0,
        };
        println!("{}", account.owner);
    }

    Rust doesn't compile this: error E0451

    error[E0451]: field `balance` of struct `Account` is private
      --> main.rs:11:9
       |
     9 |     let account = bank::Account {
       |                   ------------- in this type
    10 |         owner: String::from("Ada"),
    11 |         balance: 0,
       |         ^^^^^^^ private field

    That’s usually what you want: callers must go through a constructor such as Account::new, which can check its inputs. Enums work differently: the variants of a pub enum and their fields are all public.

    Try it yourself

    Exercise: port this to Rust

    Port this thermostat to Rust. Put it in a module named climate, and make sure code outside the module can’t set the target without going through set_target.

    Starting code in TypeScript
    thermostat.ts
    const MIN = 10;
    const MAX = 30;
    
    class Thermostat {
      #target = 20;
    
      setTarget(celsius: number): void {
        this.#target = Math.min(Math.max(celsius, MIN), MAX);
      }
    
      get target(): number {
        return this.#target;
      }
    }
    
    const thermostat = new Thermostat();
    thermostat.setTarget(35);
    console.log(`Target: ${thermostat.target}`);
    Starting code in C#
    Thermostat.cs
    var thermostat = new Thermostat();
    thermostat.SetTarget(35);
    Console.WriteLine($"Target: {thermostat.Target}");
    
    public class Thermostat
    {
        private const int Min = 10;
        private const int Max = 30;
    
        public int Target { get; private set; } = 20;
    
        public void SetTarget(int celsius) => Target = Math.Clamp(celsius, Min, Max);
    }

    Expected output

    Target: 30
    Show a hint

    Put the constants and the struct in a mod block. Mark the struct, new, set_target and target as pub, and leave the target field and the constants private. i32 has a clamp method.

    Show a solution
    mod climate {
        const MIN: i32 = 10;
        const MAX: i32 = 30;
    
        pub struct Thermostat {
            target: i32,
        }
    
        impl Thermostat {
            pub fn new() -> Self {
                Thermostat { target: 20 }
            }
    
            pub fn set_target(&mut self, celsius: i32) {
                self.target = celsius.clamp(MIN, MAX);
            }
    
            pub fn target(&self) -> i32 {
                self.target
            }
        }
    }
    
    fn main() {
        let mut thermostat = climate::Thermostat::new();
        thermostat.set_target(35);
        println!("Target: {}", thermostat.target());
    }

    Code outside climate can't set the target field directly, so set_target is the only way to change it and the clamp always runs. The constants stay private because main never needs them. The field and the getter can share the name target.