0
0
GoHow-ToBeginner · 3 min read

How to Use go get: Installing and Managing Go Packages

Use go get to download and install Go packages or modules by running go get <package-path>. It fetches the package and adds it to your module's dependencies automatically.
📐

Syntax

The basic syntax of go get is:

  • go get <package-path>: Downloads and installs the package.
  • go get -u <package-path>: Updates the package to the latest version.
  • go get <package-path>@<version>: Installs a specific version of the package.

This command works inside a Go module and updates your go.mod file automatically.

bash
go get <package-path>
go get -u <package-path>
go get <package-path>@<version>
💻

Example

This example shows how to use go get to install the popular gorilla/mux package for routing in Go web applications.

go
package main

import (
	"fmt"
	"github.com/gorilla/mux"
)

func main() {
	router := mux.NewRouter()
	fmt.Println("Router created:", router)
}
Output
Router created: &{0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000 0xc0000a6000}
⚠️

Common Pitfalls

Common mistakes when using go get include:

  • Running go get outside a module directory, which causes errors because go.mod is missing.
  • Not specifying a version when you want a specific release, leading to unexpected updates.
  • Using go get to install executables globally, which is deprecated in Go 1.17+; instead, use go install <package-path>@latest.
bash
/* Wrong: Installing executable globally (deprecated) */
go get github.com/golangci/golangci-lint/cmd/golangci-lint

/* Right: Use go install with version */
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
📊

Quick Reference

CommandDescription
go get Download and add package to module dependencies
go get -u Update package to latest version
go get @Install specific package version
go install @latestInstall executable binary (Go 1.17+)

Key Takeaways

Use go get inside a Go module to add or update packages.
Specify versions with @version to control package versions.
For installing executables, prefer go install <package>@latest over go get.
Running go get outside a module directory will cause errors.
Use go get -u to update packages to their latest versions.