CodeBlanks Logo Icon CodeBlanks

File modules

Learn the file-based module hierarchy.

File modules

In large projects modules are put in separate files. A mod ag; declaration (without a body) tells the compiler to read the content from a file:

src/
├── main.rs        // mod ag;
├── ag.rs          // pub mod istemci;
└── ag/
    └── istemci.rs // pub fn baglan() { .. }

The older layout ag/mod.rs is still valid; the two can't be used at the same time. The file system structure mirrors the module tree exactly.

Re-exporting with pub use

Even when the internal structure is deep, users can be offered short paths. pub use re-exports an item in a parent module:

// src/ag.rs
pub mod istemci;
pub use istemci::baglan;   // also reachable as ag::baglan

// main.rs
mod ag;
fn main() {
    ag::baglan();
    ag::istemci::baglan();   // both work
}

Libraries use this to keep the public API stable even when the internal file layout changes.

Practice Re-exporting

Imitate the file layout with inline modules: pub mod istemci inside mod ag, and inside it pub fn baglan() -> &'static str returning "bağlandı". Write pub use istemci::baglan; inside ag. Print the results of ag::baglan() and ag::istemci::baglan() separated by a space.

Starter code

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

Sample solution

main.rs
mod ag {
    pub mod istemci {
        pub fn baglan() -> &'static str {
            "bağlandı"
        }
    }
    pub use istemci::baglan;
}

fn main() {
    println!("{} {}", ag::baglan(), ag::istemci::baglan());
}

Expected output

bağlandı bağlandı

Questions and answers

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

1 If <code>src/ag.rs</code> exists but <code>main.rs</code> doesn't declare <code>mod ag;</code>, what happens?

  • It's included automatically
  • Compile error
  • It warns
  • The file isn't compiled at all; it isn't part of the module tree Correct answer

Explanation: In Rust files aren't found automatically; every module must be declared with mod in its parent.

2 Re-export

Question
pub mod istemci;
____ istemci::baglan;
Answer
pub mod istemci;
pub use istemci::baglan;

Explanation: pub use adds the item to the API of the module it's in.

3 File and module path

Term Meaning
src/main.rs crate
src/ag.rs crate::ag
src/ag/istemci.rs crate::ag::istemci
src/ag/mod.rs crate::ag (old layout)

All lessons in Intermediate