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?
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