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:
- Importing package from the same local module.
- Importing package from remote module.
- 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 | hello/ |
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 | # go list ./... |
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 | # Module name: example.com/fruit |
In the hello.go:
1 | import ( |
To make the import for apple and peach work, we need to edit the go.mod
file in hello folder:
1 | # In hello folder |
The hello go.mod
file will be something like:
1 | module example.com/hello |