Golang Import Package

CAUTION: When using VSC editor, please open the root directory of that go module instead of a parent directory that contains many go modules/projects, otherwise the editor will not work as expected.

There are several situations of importing package to use in your code:

  1. Importing package from the same local module.
  2. Importing package from remote module.
  3. Importing package from a different local module .

For #1 and #2, the steps are described in How to Write Go Code, this article also explains what are go package and module and the code organization.

For example, I have a go module with below file structure:

1
2
3
4
5
6
hello/
|-services/ # services package
|- service1.go # (define struct A with exported methods)
|- service2.go # (define other exported methods for struct A)
|-hello.go # main package
|-go.mod

The module name is example.com/hello, the services folder holds a separate package serivces(with 2 go files service1 and service2), main package is defined in hello.go.

If run go list ./... from hello folder, will get 2 packages:

1
2
3
# go list ./...
example.com/hello
example.com/hello/services

The hello.go imports and uses services package would be:

1
import "example.com/hello/services"

For package imported from remote module, the downloaded module is in pkg/mod subdirectory of the directory indicated by the GOPATH environment variable. To remove all downloaded modules, run:

1
go clean -modcache

For #3, please see Call your code from another module

For example, I have 2 go modules with below file structure:

1
2
3
4
5
6
7
8
9
# Module name: example.com/fruit
|- fruit/
|- apple.go # package apple with ReturnApple func
|- peach.go # package peach with ReturnPeach func
|- go.mod
# Module name example.com/hello
|- hello/
|-hello.go # package main
|-go.mod

In the hello.go:

1
2
3
4
5
6
7
8
9
10
import (
"fmt"
"example.com/fruit/apple"
"example.com/fruit/peach"
)

func main() {
fmt.Println(apple.ReturnApple())
fmt.Println(peach.ReturnPeach())
}

To make the import for apple and peach work, we need to edit the go.mod file in hello folder:

1
2
3
# In hello folder
go mod edit -replace example.com/fruit=../fruit
go mod tidy

The hello go.mod file will be something like:

1
2
3
4
5
6
7
8
module example.com/hello

go 1.18

require (
example.com/fruit v0.0.0-00010101000000-000000000000
)
replace example.com/fruit => ../fruit
0%