Lesson contents

Go — Organizing code across files

A Go module defines the import path for its packages. Give a helper an exported name so code in another package can call it.

A simple example

Call a package function

  1. Start with "a"
  2. Do this Import strings, call ToUpper
  3. Result A
The package name tells Go where to find the function.
main.go
package main

import "fmt"
import "strings"

func main() {
    fmt.Println(strings.ToUpper("a"))
}
Output
A
Advertisements

Share a function between source files

The module path in go.mod supplies the prefix for local imports. Put the helper in its own directory. Its exported name begins with an uppercase letter so package main can call it.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

Go 1.20 or later. Run these commands from the directory containing the example.

go run .
go.mod
module example.com/packing

go 1.20
boxmath/boxes.go
package boxmath

func Remaining(capacity, used int) int {
    return capacity - used
}
main.go
package main

import (
    "fmt"
    "example.com/packing/boxmath"
)

func main() {
    fmt.Println(boxmath.Remaining(8, 3))
}
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

A Tour of Go

Related tags

  • Go
  • modules
  • source files
  • imports