go mod init
Initializes a new module by creating ago.mod file in the current directory. You should provide the module path (for example, a repository path). This command sets the module root to the current directory and records the module path used for import resolution.
Example:
go mod init without an argument, Go will attempt to infer a module path from the current directory — however, providing an explicit module path is recommended for clarity and reproducibility.
go mod tidy
Keeps yourgo.mod and go.sum files in sync with the packages imported by your source code. Specifically, it will:
- add any missing module requirements needed to build the module’s packages and dependencies,
- remove requirements on modules that no longer provide relevant packages,
- update
go.sumaccordingly.
go run
Compiles and runs Go programs without leaving a permanent binary in your source tree.go run builds a temporary executable, runs it, and deletes it when the program exits. It’s ideal for quickly testing small programs or running a single file.
Examples:
go run accepts one or more files or a package path.
go build
Compiles the packages named by the import paths along with their dependencies. For apackage main, go build produces an executable. When building a single package, the resulting executable is placed in the current directory by default (unless you specify -o).
Examples:
go build flags:
-o <file>: set output file name-v: print package names as they are compiled-x: print the full commands
go install
Compiles and installs the named packages. The installed binary is placed inGOBIN if set, otherwise in $GOPATH/bin. When that directory is on your PATH, the installed executable becomes available system-wide.
Examples:
From Go 1.17 onward, installing specific versions of binaries is commonly done with
go install <pkg>@<version>. Using go install without an @version will still install the package, but go install pkg@version is the recommended pattern for reproducible installs of command binaries.go get
go get resolves the command-line arguments to packages at specific module versions, updates go.mod to require those versions, and downloads the source into the module cache. Typical uses include adding or updating dependencies and fetching modules referenced by go.mod.
Examples:
go install <pkg>@<version> over go get for reproducible installs and clearer intent.
Quick reference table
Recommended workflows and tips
- Use
go mod initto start a new project. Commit the generatedgo.modandgo.sum. - Run
go mod tidybefore committing to keep dependency metadata clean. - Use
go runfor quick experimentation andgo buildfor producing release binaries. - For installing CLI tools, prefer
go install pkg@versionto ensure reproducible installs. - Keep your
GOBINor$GOPATH/binin your PATH to run installed binaries directly.