2

Go Modules Cheat Sheet

 3 years ago
source link: https://encore.dev/guide/go.mod
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Go modules cheat sheet

by @_eandre

Quick start

# Dependency Management
go get -d github.com/path/to/module # add or upgrade dep
go get -d github.com/dep/two/[email protected] # use specific version
go get -d github.com/dep/commit@branch # use specific branch
go get -d -u ./... # upgrade all modules used in subdirs

go get -d github.com/dep/legacy@none # remove dep
# Useful commands
go mod tidy # organize and clean up go.mod and go.sum
go mod download # download deps into module cache
go mod init github.com/path/to/module # initialize new module
go mod why -m github.com/path/to/module # why is the module a dependency?
go install github.com/path/to/bin@latest # build and install a binary

Anatomy of go.mod

module github.com/my/librarygo 1.16require ( github.com/dep/one v1.0.0 github.com/dep/two/v2 v2.3.0 github.com/dep/other v0.0.0-20180523231146-b3f5c0f6e5f1 github.com/dep/legacy v2.0.0+incompatible)exclude github.com/dep/legacy v1.9.2replace github.com/dep/one => github.com/fork/oneGo import path for where the module is hostedGo version used to develop the module(to use new language features)v2 and later have the major version in the module pathA “pseudo-version” that refers toa commit and not a tagged release“incompatible” means the packagehasn’t been migrated to Go modules yetReplace this module with this onePrevent a specificmodule versionfrom being used

Minimal Version Selection (MVS)

To build a program Go needs to know exactly which dependencies you need, and which version to use.

Go uses MVS as a predictable and simple way to decide which version to use.

It works like this:

  1. The module you’re running from is the “main module”
  2. Find all dependencies the main module needs (recursively, using the dependencies’ go.mod files)
  3. For each dependency, use the greatest version that any go.mod explicitly specified

Example

go-mod-mvs.svg

In this example, the main module depends on A 1.0 and B 2.1.

Since B 2.1 depends on A 1.1, this is the version of A that will be used.

Since A 1.1 is used, it also pulls in C 1.1.

The final dependency list is:

  • A 1.1
  • B 2.1
  • C 1.1

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK