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:
|
|
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
:
|
|
And create a file pkg/greeter/greeter.go
:
|
|
Time to use our ‘internal’ package, by main.go
:
|
|
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.
|
|
|
|
Just don’t forget to open your package’s root directory in VS Code ;)
References:
Wed Sep 6, 2023 / 280 words / Golang Programming