Defining modules
- Rust course
- Intermediate
- Lesson 71/115
- 4 min
Define modules with mod.
Defining modules
Modules split code into named sections and form a tree. The root of the tree is the crate (main.rs or lib.rs):
mod matematik {
pub fn kare(x: i32) -> i32 {
x * x
}
pub mod istatistik {
pub fn ortalama(v: &[f64]) -> f64 {
v.iter().sum::<f64>() / v.len() as f64
}
}
}
// crate
// └── matematik
// ├── kare
// └── istatistik
// └── ortalamaItems are reached by path: matematik::kare(7), matematik::istatistik::ortalama(&v).
Why modules?
Modules do three jobs: they keep related code together, prevent name clashes (daire::alan and kare::alan can coexist) and draw a privacy boundary: only the API marked pub is visible outside, and internal details can change freely.
mod sayac {
fn ic_yardimci() {} // module only
pub fn artir(n: u32) -> u32 { n + 1 }
}Practice First module
Define pub fn kare(x: i32) -> i32 inside mod matematik and print the result of matematik::kare(7) in main.
Starter code
fn main() {
// buraya yaz
}Sample solution
mod matematik {
pub fn kare(x: i32) -> i32 {
x * x
}
}
fn main() {
println!("{}", matematik::kare(7));
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if <code>main</code> accesses a non-<code>pub</code> function inside a module?
- It warns
- Runtime error
- E0603: the function is private Correct answer
- It works
Explanation: Privacy is the default; a parent can't see its child's private items. A child module can see its ancestors' items.
2 Open a module
____ matematik {
pub fn kare(x: i32) -> i32 { x * x }
}
mod matematik {
pub fn kare(x: i32) -> i32 { x * x }
}
Explanation: A module is defined with the mod keyword.
3 Path and target
| Term | Meaning |
|---|---|
matematik::kare |
Function in the module |
matematik::istatistik |
Inner module |
crate |
Root of the tree |
fn ic_yardimci (no pub) |
Module only |