Understand the contract

A module contains one or more packages and has a go.mod file at its root. A package usually consists of Go source files in a single directory. Its import path combines the module path with the package directory. This distinction explains why a project can have several packages but only one go.mod.

Create the example in a new module initialized with go mod init example.com/hello. Put main.go at the root and hello.go inside a greeting directory. The exported Hello function begins with an uppercase letter so that main can call it from another package.

Work through the example

Running go run . compiles the command and its imported package together. Both files use only local code and the standard library. If you later add an external dependency, go mod tidy reconciles the dependency metadata with imports and tests; review its changes to go.mod and go.sum.

// greeting/hello.go
package greeting

func Hello() string { return "Hello, Go!" }

// main.go (a separate file)
package main

import (
    "fmt"
    "example.com/hello/greeting"
)

func main() { fmt.Println(greeting.Hello()) }

Watch this boundary

Packages cannot form import cycles. If greeting imports the main package to access a shared value, the dependency direction becomes a problem. Pass the needed value as a parameter or move shared behavior into a lower-level package instead of adding a circular import.

Practice with a changed input

Add a name parameter to Hello and call it from main. Rename Hello to hello and observe why the other package can no longer access it.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services