ataraskov.dev

About everything and nothing


Local modules in Go

Most of the Go code/project examples are organized as publicly available modules on GitHub. Historically, Go played nicely with Git-enabled repositories. But it’s not that obvious how to play around on a local machine without pushing any code to a remote repository. At least it wasn’t for me when I started playing with Go. Let’s review how it’s done in Go 1.13+.

First of all, we need to create a directory and initialize a module. We will name our project playground, why not. The go mod init ... command will create a go.mod file with module name and Go version used:

1
2
3
mkdir playground
cd playground
go mod init playground

 

Write some code. Create an internal package (ideally we should write a test first sure, will pretend it’s done already). For example pkg/greeter:

1
mkdir -p  pkg/greeter

And create a file pkg/greeter/greeter.go:

1
2
3
4
5
package greeter

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

 

Time to use our ‘internal’ package, by main.go:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import (
	"fmt"
	"playground/pkg/greeter"
)

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

Notice the import path for the pkg/greeter. The trick is to include the root package name in relative imports, which is different from how it’s done in other languages.

Our files tree looks like this now, and Go compiler is happy.

1
2
3
4
5
6
7
$ tree
.
├── go.mod
├── main.go
└── pkg
    └── greeter
        └── greeter.go
1
2
$ go run main.go
Hello!

 

Just don’t forget to open your package’s root directory in VS Code ;)

References:

Wed Sep 6, 2023 / 280 words / Golang Programming