Create a Go module
This tutorial introduces fundamental features of Go modules. If you’re new to Go, it’s recommended to complete the Get started with Go tutorial first, which covers the go command, Go modules, and basic Go code execution.
In this tutorial, you’ll create two modules:
- A library module intended for reuse by other libraries or applications.
- A caller application module that uses the library.
The tutorial includes seven parts, each illustrating a distinct aspect of Go’s module system:
- Create a module — Write a small module with functions callable from other modules.
- Call your code from another module — Import and use your new module.
- Return and handle an error — Add basic error handling.
- Return a random greeting — Work with slices (dynamic arrays).
- Return greetings for multiple people — Use maps for key/value storage.
- Add a test — Leverage Go’s built-in unit testing.
- Compile and install the application — Build and install your application locally.
Prerequisites
- Some programming experience (functions, loops, arrays).
- A code editor. Popular choices include VS Code (free), GoLand (paid), and Vim (free).
- A command terminal (works on Linux, Mac, PowerShell, or Command Prompt on Windows).
1. Start a module that others can use
A module in Go groups related packages under a single dependency unit. It specifies:
- The Go version supported
- Module dependencies
As the module evolves, updates can be published for others to use.
Procedure:
-
Open a terminal and navigate to your home directory:
-
On Linux/Mac:
cd -
On Windows:
cd %HOMEPATH%
-
-
Create and enter a directory for your module:
mkdir greetings cd greetings -
Initialize a new module. Use a module path (e.g.,
example.com/greetings) that corresponds to a repository path if you plan to publish it:go mod init example.com/greetingsThis creates a
go.modfile with the module name and supported Go version. -
In your editor, create a file named
greetings.goand insert:package greetings import "fmt" // Hello returns a greeting for the named person. func Hello(name string) string { message := fmt.Sprintf("Hi, %v. Welcome!", name) return message }This defines a
greetingspackage with an exportedHellofunction.
[Next Steps]
Continue with the remaining parts of the tutorial as listed, such as calling your module from another module, adding error handling and tests, and finally compiling and installing your application.