为什么自 Go 1.17 以来 go.mod 中有两个 "require" 块?

Why there are two "require" blocks in go.mod since Go 1.17?

我创建了一个小的 go 应用程序。几天前,我从 go 1.15 升级到 1.17,我还用 go get -u 升级了软件包。更改后,我的 go.mod 文件中有 2 个 require 块。为什么?这是什么意思?没问题还是哪里坏了?

应用程序仍然可以正确构建。

go.mod 文件:

module github.com/jozo/simple-pomodoro

go 1.17

require (
    fyne.io/fyne/v2 v2.1.0
    github.com/dsnet/golib/memfile v1.0.0
    github.com/faiface/beep v1.1.0
    github.com/fsnotify/fsnotify v1.5.1 // indirect
    github.com/go-gl/gl v0.0.0-20210905235341-f7a045908259 // indirect
    github.com/go-gl/glfw/v3.3/glfw v0.0.0-20210727001814-0db043d8d5be // indirect
    github.com/godbus/dbus/v5 v5.0.5 // indirect
    github.com/hajimehoshi/oto v1.0.1 // indirect
    github.com/srwiley/oksvg v0.0.0-20210519022825-9fc0c575d5fe // indirect
    github.com/srwiley/rasterx v0.0.0-20210519020934-456a8d69b780 // indirect
    github.com/yuin/goldmark v1.4.1 // indirect
    golang.org/x/exp v0.0.0-20210916165020-5cb4fee858ee // indirect
    golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d // indirect
    golang.org/x/mobile v0.0.0-20210924032853-1c027f395ef7 // indirect
    golang.org/x/net v0.0.0-20210929193557-e81a3d93ecf6 // indirect
    golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 // indirect
    golang.org/x/text v0.3.7 // indirect
    gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)

require (
    github.com/davecgh/go-spew v1.1.1 // indirect
    github.com/fredbi/uri v0.0.0-20181227131451-3dcfdacbaaf3 // indirect
    github.com/goki/freetype v0.0.0-20181231101311-fa8a33aabaff // indirect
    github.com/pkg/errors v0.9.1 // indirect
    github.com/pmezard/go-difflib v1.0.0 // indirect
    github.com/stretchr/testify v1.7.0 // indirect
)

因为在 Go 1.17 中,模块图已更改为启用 p运行ing 和延迟加载。第二个 require 块包含间接依赖项。

https://golang.org/doc/go1.17#go-command

If a module specifies go 1.17 or higher, the module graph includes only the immediate dependencies of other go 1.17 modules, not their full transitive dependencies. [...]

[...] If a module specifies go 1.17 or higher in its go.mod file, its go.mod file now contains an explicit require directive for every module that provides a transitively-imported package. (In previous versions, the go.mod file typically only included explicit requirements for directly-imported packages.)

Because the number of explicit requirements may be substantially larger in an expanded Go 1.17 go.mod file, the newly-added requirements on indirect dependencies in a go 1.17 module are maintained in a separate require block from the block containing direct dependencies.

注意:您在问题中发布的 go.mod 文件在第一个 require 块中具有 //indirect 依赖项。我怀疑,根据引用文档中的“新添加”措辞,这是因为那些 //indirect 依赖项已经列在那里并且 go mod tidy 没有重新排列它们。如果你:

  • 手动删除其中一个
  • and/or 重新创建 go.mod 文件并将 Go 版本设置为 1.17 或更高
  • and/or 运行 go mod tidy -go=1.17

然后它将在两个块中分离直接和 //indirect 依赖项。无论如何,这是一种视觉上的便利,文档没有强制创建两个单独的块。


其他参考资料: