Golang modules
17 August 2024 (Updated 17 August 2024)
In a nutshell
A module is a collection of Go packages stored in a file tree with a go.mod
file at its root.
The go.mod
file defines the module’s module path, which is also the import parth for the root directory and its dependency requirements (other modules needed for a successful build).
Create a module
Syntax:
go mod init <prefix>/<module-name>
Example:
go mod init sajadtorkamani/go-playground
This will create a go.mod
file with the following content:
module sajadtorkamani/go-playground
go 1.22.6 // or whatever Go version you have
Install a dependency
Syntax:
go get <module>[@version>]
Example:
go get rsc.io/quote
This will add rsc.io/quote
and any of its dependencies to go.mod
:
module sajadtorkamani/go-playground
go 1.22.6
require (
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect
rsc.io/quote v1.5.2 // indirect
rsc.io/sampler v1.3.0 // indirect
)
List available versions of a module
go list -m -versions <module-name>
Remove unuse dependencies
go mod tidy
Tagged:
Golang