Home > database >  go build -mod=mod with no go.mod
go build -mod=mod with no go.mod

Time:01-12

If I run a command similar to the following:

go build -mod=mod -o xyz.exe github.com/some/go/tool

And I'm in a directory with a go.mod, I noticed that the go.mod will be updated with a reference to github.com/some/go/tool, and xyz.exe will be built. So the go.mod being used is the one in the current directory.

However, if I change to some empty tmp folder with no go.mod, the build still succeeds and no go.mod is generated or updated.

My question is: in the latter case, what go.mod is used? Does go use the one from github.com/some/go/tool? And, is this documented somewhere?

CodePudding user response:

When you run the command go build -mod=mod -o xyz.exe github.com/some/go/tool in a directory with an existing go.mod file, Go will use the go.mod in the current directory, and any new dependencies added as a result of building the github.com/some/go/tool package will be added to that go.mod file.

However, when you run the command in a directory without a go.mod file, Go will still be able to build the package, but it will not create or update a go.mod file in the current directory.

When Go is building a package that is not in the current module (the module defined by the current directory's go.mod), it will use the go.mod file of the package that you are building if present. In this case github.com/some/go/tool should have it's own go.mod file and it will be used when building and resolving the dependencies.

This behavior of Go is specified in the go help build documentation, under the section "Modules" specifically.

https://golang.org/cmd/go/#hdr-Modules__module_versions__and_more

CodePudding user response:

let's take a look at what go.mod does:

Take windows-os as an example:

go mod file like:

module xxx

go 1.19

require github.com/mitchellh/mapstructure v1.5.0

if you run

go build -mod=mod  xxx

it will be download mapstructure in C:\Users\{username}\go\pkg\mod\github.com\mitchellh\[email protected]

Next, if you delete the go.mod, \go\pkg\...\mapstructure still exists.

go will look up \go\pkg\ and go Root, when go run/build.

so it can build/run even there is no go.mod

if delete \go\pkg\...\mapstructure in local, it will can't run/build

go mod can build consistently in different environments(different pc/os).and deal different version and package dependencies

  • Related