GoLang使用保留的文件名吗?

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

Does GoLang use reserved filenames?

问题

在CI/CD流水线中,我们有一个Go脚本,在构建可交付的构件之前进行一些预处理。如果我将脚本命名为main.go,在Go语言世界中是否算是不好的做法?我不明白是否有任何与脚本的实际文件名相关的命名空间问题。

我知道main.go是脚本,main_test.go是单元测试,所以我有些担心并正在寻求指导。

例如,如果我在shell(MacOS bash)中执行以下命令:go test
这将执行main.go脚本的单元测试,这让我相信main可能是某种保留的文件名。不过我可能错了。

你有什么想法?

英文:

In a CI/CD pipeline, we have a Go script that does some preprocessing prior to actually building our deliverable artifacts. If I name the script main.go is that a foul in the GoLang world or is that OK? I do not understand if there are any namespace concerns that tie back to the actual filename of the script.

I know that main.go being the script, main_test.go is the Unit Tests so I am leary and looking for guidance.

For example, if I execute from the shell (MacOS bash) the following: go test
This executes the unit tests for the main.go script which leads me to believe that main is some sort of reserved file name. I could easily be wrong though.

Thoughts?

答案1

得分: 1

文件名main.go并没有特殊含义。

Go会检测文件是否属于测试文件,是因为文件名以_test.go结尾,并且会检测包是否为可执行文件(而不是库),是因为包名为main(也就是以package main开头)。你可以在库中使用名为main.go的文件。

你可以在go/build的源代码中看到go build在文件中寻找的内容。它只检查了_test后缀,代码如下:

https://cs.opensource.google/go/go/+/refs/tags/go1.17.3:src/go/build/build.go;l=895;drc=deb3403ff52b8833df6c4e2f82cbdddeb13573dd

isTest := strings.HasSuffix(name, "_test.go")
英文:

The filename main.go is not special.

Go detects that a file is part of a test because it ends in _test.go, and detects that a package is a binary (instead of a library) because the package name is main (in other words, it starts with package main). You can use a file named main.go in a library.

You can see in the source code for go/build what go build looks for in files. It only has a check for the _test suffix, here:

https://cs.opensource.google/go/go/+/refs/tags/go1.17.3:src/go/build/build.go;l=895;drc=deb3403ff52b8833df6c4e2f82cbdddeb13573dd

isTest := strings.HasSuffix(name, "_test.go")

huangapple
  • 本文由 发表于 2021年12月9日 01:56:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/70279625.html
匿名

发表评论

匿名网友

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

确定