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
- Start with "a"
- Do this Import strings, call ToUpper
- Result A
package main
import "fmt"
import "strings"
func main() {
fmt.Println(strings.ToUpper("a"))
}
A
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.
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 .
module example.com/packing
go 1.20
package boxmath
func Remaining(capacity, used int) int {
return capacity - used
}
package main
import (
"fmt"
"example.com/packing/boxmath"
)
func main() {
fmt.Println(boxmath.Remaining(8, 3))
}
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.