14 · Modules
mod creates a named namespace. Items inside a module are private by default — pub makes them accessible to callers. use brings items into scope without a full path. Modules map to files: a mod math; declaration in main.cssl loads math.cssl from the same directory.
// math.cssl — a module filemod math { // Private helper — not accessible outside this module. fn two_pi() -> f32 { 6.28318 }
pub fn circle_area(r: f32) -> f32 { 3.14159 * r * r }
pub fn circle_circumference(r: f32) -> f32 { two_pi() * r }
// A sub-module. pub mod stats { pub fn mean(values: &[f32]) -> f32 { let sum: f32 = values.iter().sum(); sum / values.len() as f32 } }}
// main.cssluse math::{circle_area, circle_circumference};use math::stats::mean;
fn main() !io { let r = 3.0_f32; println!("area = {:.2}", circle_area(r)); // 28.27 println!("circumference = {:.2}", circle_circumference(r)); // 18.85
let data = [1.0_f32, 2.0, 3.0, 4.0, 5.0]; println!("mean = {:.1}", mean(&data)); // 3.0
// Full path also works without use. println!("area again = {:.2}", math::circle_area(2.0)); // 12.57}Output
Section titled “Output”area = 28.27circumference = 18.85mean = 3.0area again = 12.57What the compiler sees
Section titled “What the compiler sees”two_pi is invisible outside math — calling math::two_pi() from main.cssl is a compile error. use does not run any code; it is a compile-time name resolution directive. Circular use imports between modules are detected and rejected at compile time. The module tree mirrors the file system: mod math::stats lives in either math/stats.cssl or math.cssl as a nested mod stats { ... } block — both forms are equivalent.
You’ve reached the end of Sigil by Example. Head to §B Language Reference for the full specification, or return to 01 · Hello World to review the basics.