CodeBlanks Logo Icon CodeBlanks

Summary - Modules

Combine mod, use and pub to set up a multi-file crate.

Modules summary

mod builds a module tree; items are private by default and opened with pub (struct fields individually). use shortens paths, as renames, pub use re-exports. Paths can start with crate::, super:: or self::. Modules can go in separate files (ag.rs, ag/istemci.rs). Fine-grained visibility: pub(crate), pub(super).

A private inner module

Library authors put details into private inner modules and expose a small surface:

mod kutuphane {
    mod ic {
        pub fn gizli_hesap(x: i32) -> i32 {
            x * 3
        }
    }

    pub fn hesapla(x: i32) -> i32 {
        ic::gizli_hesap(x) + 1
    }
}

// kutuphane::ic::gizli_hesap(4);   // error: ic is private
println!("{}", kutuphane::hesapla(4));   // 13

Practice Small surface

Write the kutuphane module above: gizli_hesap in the private ic module, and pub fn hesapla outside. Print the result of kutuphane::hesapla(4).

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
mod kutuphane {
    mod ic {
        pub fn gizli_hesap(x: i32) -> i32 {
            x * 3
        }
    }

    pub fn hesapla(x: i32) -> i32 {
        ic::gizli_hesap(x) + 1
    }
}

fn main() {
    println!("{}", kutuphane::hesapla(4));
}

Expected output

13

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you fully hide an inner module and expose just one function?

  • It isn't possible
  • Leave the module non-pub and wrap it with a pub fn above, or pub use it Correct answer
  • Make the module pub
  • Use unsafe

Explanation: The pub items of a private module can only be used by code that can see that module; exposing them needs a door from the parent.

2 Crate-wide visibility

Question
____(crate) fn yardimci() {}
Answer
pub(crate) fn yardimci() {}

Explanation: pub(crate) opens the item only within the same crate.

3 Group summary

Term Meaning
mod x { } Module
pub Exposes
use a::b Shortcut
pub use Re-export

All lessons in Intermediate