Go Modules

Modules

To develop in a module environment, run the following commands. The go mod init command creates a go.mod file in the current directory.

$ mkdir hello
$ cd hello
$ go mod init hello
$ vi main.go

Create the program.

package main

import "fmt"

func main() {
    fmt.Println("Hello world!")
}

Run the program.

$ go run .
Hello world!

To use a published module, enter the following command. Modules are stored in the directory specified by the GOPATH environment variable. Its default value is $HOME/go.

% go get golang.org/x/example
go: downloading golang.org/x/example v0.0.0-20220412213650-2e68773dfca0
go: added golang.org/x/example v0.0.0-20220412213650-2e68773dfca0

Use the module in the program by modifying the existing main.go file as follows.

package main

import "fmt"
import "golang.org/x/example/stringutil"

func main() {
    fmt.Println(stringutil.Reverse("Hello world!"))
}

Run it.

$ go run .
!dlrow olleH

You can assign a package alias in an import declaration as follows. This avoids conflicts when package names overlap.

import (
    "fmt"
    gstr "golang.org/x/example/stringutil"
)