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:

Module Declaration

Basic Syntax

Each Golo file must start with a module declaration:

module examples.MathUtils

Module naming conventions:

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("<", "&lt;"): replaceAll(">", "&gt;")
}

# 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:

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