Module System and Imports in GoloScript
This guide covers Golo-Scriptβs module and import system, allowing you to organize your code into reusable modules.
Overview
Golo-Scriptβs module system allows you to:
- Organize code into logical, reusable units
- Import and use functions from other modules
- Create utility function libraries
- Maintain a clean and modular codebase
Module Declaration
Basic Syntax
Each Golo file must start with a module declaration:
module examples.MathUtils
Module naming conventions:
- Uses dot notation (
.) to represent hierarchy - Typically corresponds to directory structure
- Starts with lowercase for package, uppercase for module
Example: Simple Module
File: examples/imports/math_utils.golo
module examples.MathUtils
function square = |x| {
return x * x
}
function cube = |x| {
return x * x * x
}
function add = |a, b| {
return a + b
}
Module-File Correspondence
| Module Declaration | File Path |
|---|---|
module examples.MathUtils |
examples/imports/math_utils.golo |
module examples.StringUtils |
examples/imports/string_utils.golo |
module app.services.Database |
app/services/database.golo |
Note: The module name uses CamelCase (MathUtils) while the file uses snake_case (math_utils.golo).
Importing Modules
Basic Import
To use functions from another module, import it at the top of your file:
module examples.ImportTest
import examples.MathUtils
function main = |args| {
println("square(5) =", square(5)) # Uses function from MathUtils
println("cube(3) =", cube(3)) # Uses function from MathUtils
println("add(10, 20) =", add(10, 20)) # Uses function from MathUtils
}
Multiple Imports
You can import multiple modules:
module examples.Utils
import examples.MathUtils
import examples.StringUtils
function processData = |x| {
let squared = square(x) # From MathUtils
let result = what_it_could_be(str(squared)) # From StringUtils
return result
}
Functions Directly Available
After importing, all exported functions from the module become directly available:
import examples.MathUtils
# No need to prefix with module name
let result = square(5) # β Works
# let result = MathUtils.square(5) # β Not necessary in Golo
Module Organization
Recommended Directory Structure
project/
βββ main.golo # Application entry point
βββ utils/
β βββ math_utils.golo # module utils.MathUtils
β βββ string_utils.golo # module utils.StringUtils
β βββ date_utils.golo # module utils.DateUtils
βββ models/
β βββ user.golo # module models.User
β βββ product.golo # module models.Product
βββ services/
βββ database.golo # module services.Database
βββ api.golo # module services.Api
Example: Utility Library Module
File: examples/imports/math_utils.golo
module examples.MathUtils
function square = |x| {
return x * x
}
function cube = |x| {
return x * x * x
}
function add = |a, b| {
return a + b
}
function multiply = |a, b| {
return a * b
}
function power = |base, exponent| {
var result = 1
var i = 0
while i < exponent {
result = result * base
i = i + 1
}
return result
}
Practical Examples
Example 1: Math Utilities Module
File: examples/imports/math_utils.golo
module examples.MathUtils
function square = |x| {
return x * x
}
function cube = |x| {
return x * x * x
}
function add = |a, b| {
return a + b
}
Example 2: String Utilities Module
File: examples/imports/string_utils.golo
module examples.StringUtils
# Data type detection
function what_it_could_be = |item| {
return match {
when item: contains("@") then "an email?"
when item: startsWith("+33") then "a French phone number?"
when item: startsWith("+1") then "a US phone number?"
when item: startsWith("http://") then "an HTTP website URL?"
when item: startsWith("https://") then "an HTTPS website URL?"
when item: startsWith("ftp://") then "an FTP URL?"
otherwise "I have no clue, mate!"
}
}
# Email validator
function is_valid_email = |email| {
let trimmed = email: trim()
if not trimmed: contains("@") {
return false
}
let parts = trimmed: split("@")
if parts: length() != 2 {
return false
}
let localPart = parts: get(0)
if localPart: isEmpty() {
return false
}
let domainPart = parts: get(1)
if not domainPart: contains(".") {
return false
}
return true
}
# URL normalizer
function normalize_url = |url| {
let trimmed = url: trim()
if not trimmed: contains("://") {
return "http://" + trimmed
}
return trimmed
}
# String sanitizer
function sanitize_input = |input| {
return input: trim(): replaceAll("<", "<"): replaceAll(">", ">")
}
# Word counter
function count_words = |text| {
let trimmed = text: trim()
if trimmed: isEmpty() {
return 0
}
let words = trimmed: split(" ")
return words: length()
}
# Title case converter
function to_title_case = |text| {
let words = text: toLowerCase(): split(" ")
var result = ""
var first = true
foreach word in words {
if not first {
result = result + " "
}
if word: length() > 0 {
let firstChar = word: charAt(0): toUpperCase()
if word: length() > 1 {
result = result + firstChar + word: substring(1)
} else {
result = result + firstChar
}
}
first = false
}
return result
}
# Truncate string with ellipsis
function truncate = |text, maxLen| {
if text: length() <= maxLen {
return text
}
if maxLen <= 3 {
return text: substring(0, maxLen - 1)
}
return text: substring(0, maxLen - 4) + "..."
}
# Extract file extension
function get_file_extension = |filename| {
let dotIndex = filename: lastIndexOf(".")
if dotIndex == -1 {
return ""
}
return filename: substring(dotIndex + 1)
}
# Create slug from text
function slugify = |text| {
let lower = text: toLowerCase(): trim()
let spaces_to_dashes = lower: replaceAll(" ", "-")
return spaces_to_dashes
}
# Case-insensitive string comparison
function strings_equal_ignore_case = |str1, str2| {
return str1: equalsIgnoreCase(str2)
}
Example 3: Module Combining Multiple Imports
File: examples/imports/utils.golo
module examples.Utils
import examples.MathUtils
import examples.StringUtils
# Wrapper function using imported functions
function squareAndCube = |x| {
return [square(x), cube(x)]
}
# Function combining math and string utilities
function formatNumber = |n| {
let squared = square(n)
return "Square: " + str(squared)
}
Example 4: Using Imported Modules
File: examples/imports/import_test.golo
module examples.ImportTest
import examples.MathUtils
function main = |args| {
println("Testing module imports...")
println()
println("square(5) =", square(5))
println("cube(3) =", cube(3))
println("add(10, 20) =", add(10, 20))
println()
println("Import test complete!")
}
Best Practices
1. One Module Per File
Each file should contain exactly one module:
# Good
# file: math_utils.golo
module examples.MathUtils
function square = |x| { x * x }
2. Consistent Naming
Follow these naming conventions:
- Module name:
PascalCase(e.g.,MathUtils,StringUtils) - File name:
snake_case(e.g.,math_utils.golo,string_utils.golo) - Function name:
snake_case(e.g.,square,is_valid_email)
3. Organize by Functionality
Group related functions in the same module:
# Good: All string functions together
module utils.StringUtils
function trim = |s| { ... }
function uppercase = |s| { ... }
function lowercase = |s| { ... }
# Avoid: Unrelated functions in same module
module utils.Mixed
function trim = |s| { ... }
function square = |x| { ... } # Should be in MathUtils
4. Use Clear Imports
Import only what you need and import at the top of the file:
module app.Main
# All imports at the top
import utils.MathUtils
import utils.StringUtils
import services.Database
function main = |args| {
# Main code here
}
5. Avoid Circular Dependencies
Donβt create circular dependencies between modules:
# Avoid
# moduleA.golo
module moduleA
import moduleB # β moduleA depends on moduleB
# moduleB.golo
module moduleB
import moduleA # β moduleB depends on moduleA (circular!)
6. Create Utility Modules
Create reusable utility modules for common functions:
# utils/validators.golo
module utils.Validators
function is_valid_email = |email| { ... }
function is_valid_phone = |phone| { ... }
function is_valid_url = |url| { ... }
7. Document Modules
Use comments to document the moduleβs purpose and usage:
module utils.MathUtils
----
Math Utilities Module
Provides commonly used mathematical functions
for basic arithmetic operations
----
----
Calculates the square of a number
Parameter: x - the number to square
Returns: xΒ²
----
function square = |x| {
return x * x
}
8. Test Modules Separately
Create test files for each module:
project/
βββ utils/
β βββ math_utils.golo
β βββ string_utils.golo
βββ tests/
βββ math_utils_test.golo
βββ string_utils_test.golo
Importing Standard Go Modules
Golo-Script can also import standard Go packages:
import gololang.AnsiCodes # Built-in module for ANSI codes
function main = |args| {
fg_red()
println("Red text!")
reset()
}
Quick Reference
Module Declaration Syntax
module package.ModuleName
Import Syntax
import package.ModuleName
Complete Minimal Example
Module (math_utils.golo):
module utils.MathUtils
function add = |a, b| {
return a + b
}
Usage (main.golo):
module main
import utils.MathUtils
function main = |args| {
println(add(5, 3)) # Output: 8
}
Β© 2026 GoloScript Project | Built with Gu10berg
Subscribe: π‘ RSS | βοΈ Atom