Modules
Why Modules?
Section titled “Why Modules?”As programs grow, you need ways to split code across files, avoid name collisions, and control what’s visible to the outside world. Zap’s module system is file-based and explicit.
Importing Modules
Section titled “Importing Modules”import std.io // import the io module from the standard libraryimport std.collections // import the collections module
fn main() { io.println("Hello from io!")}Selective Imports
Section titled “Selective Imports”import std.io { println, read_line }
fn main() { println("What's your name?") let name = read_line()}Aliased Imports
Section titled “Aliased Imports”import std.collections as col
let list = col.List.new()Creating Your Own Modules
Section titled “Creating Your Own Modules”Every .zap file is a module. The file name is the module name:
my_project/├── main.zap├── math.zap└── utils/ ├── strings.zap └── files.zapimport mathimport utils.strings
fn main() { print(math.add(2, 3)) print(strings.capitalize("hello"))}Exports
Section titled “Exports”By default, all top-level declarations in a module are private. Use pub
to make them accessible:
pub fn add(a: Int, b: Int) -> Int { a + b}
fn internal_helper() { // not visible outside this module}Nested Modules
Section titled “Nested Modules”Directories create module hierarchies:
pub fn capitalize(s: String) -> String { // ...}
// Access as: utils.strings.capitalize(...)Module Conventions
Section titled “Module Conventions”| Convention | Description |
|---|---|
| One module per file | Keep modules focused and small |
pub only what’s needed |
Minimise your public API surface |
| Group related modules | Use directories for logical grouping |
main.zap as entry point |
The compiler looks for main() here |
Next Steps
Section titled “Next Steps”Explore the Standard Library to see what modules ship with Zap.