What does this command do 'GOFLAGS=-mod=mod'?

huangapple go评论90阅读模式
英文:

What does this command do 'GOFLAGS=-mod=mod'?

问题

我正在尝试创建一个用于构建Go应用程序的Taskfile.yml文件,但我不太理解在执行go build main.go之前为什么需要"GOFLAGS=-mod=mod"命令。

参考链接:https://dev.to/aurelievache/learning-go-by-examples-part-3-create-a-cli-app-in-go-1h43

英文:

I am trying to make a Taskfile.yml file for building go application, but I can't quite understand the need of "GOFLAGS=-mod=mod" command before go build main.go.

reference: https://dev.to/aurelievache/learning-go-by-examples-part-3-create-a-cli-app-in-go-1h43

答案1

得分: 7

所以这里有两件事情:

  • GOFLAGS

    • 这实际上是一个环境变量(如果你不明白环境变量是什么,可以将其视为可以被当前环境中的任何进程访问的值。这些值由操作系统维护)。
    • 所以这个GOFLAGS变量是一个以空格分隔的标志列表,这些标志将自动传递给相应的go命令。
    • 我们在这里设置的标志是mod,这个标志适用于go build命令,可能不适用于其他go命令。
    • 如果你想知道go是如何实现这个的,可以参考这个变更请求
    • 由于我们将其作为命令的一部分进行了提及,这个环境变量是临时设置的,实际上并没有导出。
  • go build期间,设置-mod=mod标志实际上是做什么?

    • -mod标志控制是否可以自动更新go.mod文件以及是否使用vendor目录。
    • -mod=mod告诉go命令忽略vendor目录,并自动更新go.mod文件,例如当导入的包没有被任何已知模块提供时。
    • 参考这里

因此,以下命令:

GOFLAGS="-mod=mod" go build main.go

等同于

go build -mod=mod main.go
英文:

So there are two things here

  • GOFLAGS
    • this is nothing but an environment variable(if you don't understand what an environment variable is, think of it like a value that can be accessed by any process in your current environment. These values are maintained by the OS).
    • So this GOFLAGS variable has a space separated list of flags that will automatically be passed to the appropriate go commands.
    • The flag we are setting here is mod, this flag is applicable to the go build command and may not be applicable to other go commands.
    • If you are curious how go does this, refer to this change request
    • Since we are mentioning this as part of the command, this environment variable is temporarily set and is not actually exported.
  • what does setting -mod=mod flag, actually do during go build?
    • The -mod flag controls whether go.mod may be automatically updated and whether the vendor directory is used.
    • -mod=mod tells the go command to ignore the vendor directory and to automatically update go.mod, for example, when an imported package is not provided by any known module.
    • Refer this.

Therefore

GOFLAGS="-mod=mod" go build main.go

is equivalent to

go build -mod=mod main.go

huangapple
  • 本文由 发表于 2022年2月15日 13:49:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/71121641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定