无go.mod目录执行go build -mod=mod时使用哪个go.mod?
Great question—this is a common point of confusion when working with Go modules. Let’s unpack each part of your question clearly:
1. Which go.mod is used when running the command in an empty directory?
When you run go build -mod=mod -o xyz.exe github.com/some/go/tool in a directory without a go.mod, Go enters what’s effectively a temporary module context. It doesn’t create or use a local go.mod file at all. Instead, it directly resolves the target module (github.com/some/go/tool) and uses its dependency graph to build the binary.
All dependencies are pulled from Go’s module cache (located at $GOPATH/pkg/mod by default) based on the versions defined in the target module’s configuration.
2. Does it use the go.mod from github.com/some/go/tool?
Absolutely. Go will fetch the github.com/some/go/tool module (including its go.mod file) from the module proxy or version control system, then use that go.mod to determine exactly which versions of its dependencies need to be included in the build. This ensures the binary you get matches the dependency versions the tool’s maintainers specified.
3. Is this behavior documented officially?
Yes, this is covered in Go’s official module documentation and the go build command docs. Here’s the key context:
When building a module path (like
github.com/some/go/tool) instead of a local package, and there’s no go.mod in the current directory, Go operates in a temporary module mode. It uses the target module’s go.mod to resolve dependencies, and doesn’t modify any local files (including not creating a go.mod).
The -mod=mod flag here reinforces this behavior: it tells Go to use module mode explicitly (even if you’re not in a module directory) and resolve dependencies based on the module’s go.mod rather than a vendor directory or cached dependencies.
内容的提问来源于stack exchange,提问作者craig65535

