Understand Module in Golang.
Code example
1 | //hello.go |
1 | //hello_test.go |
1 | //go.mod |
Use Go Modules
What is module?
1 | module:a collection of Go packages |
The Running ENV for a module:
1 | 1. outside $GOPATH/src <-- |
How to creating a new module:
1 | 1. create you file. // status: contains a package |
- Packages in subdirectories have import paths consisting of the module path plus the path to the subdirectory.
- So you don't need to run go mod init in subdirectories.
Understand go.mod content:
1 | example.com/hello //main module |
How to import dependencies module:
1 | import "rsc.io/quote" |
How to upgrading dependencies:
1 | // here is a example to upgrade text and sampler |
Now depends on both rsc.io/quote and rsc.io/quote/v3.
why here is V3?, because:
- Each different major version (v1, v2, and so on) of a Go module uses a different module path
- v3 of rsc.io/quote = rsc.io/quote/v3, Know more visit here
You can have v1, v2, v3 in same module, but can't with v1.1 and v1.2
To know what new changes in new version, type go doc rsc.io/quote/v3.
Remove no need module:
1 | go list -m all # check |
Conclusion
- go mod init creates a new module, initializing the go.mod file that describes it.
- go build, go test, and other package-building commands add new dependencies to go.mod as needed.
- go list -m all prints the current module’s dependencies.
- go get changes the required version of a dependency (or adds a new dependency).
- go mod tidy removes unused dependencies.