生成的go文件的名称

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

Name for a generated go file

问题

我正在生成一个Go文件(包含构建版本等常量),以便这些常量可以在其他包中使用。我创建了一个小工具,可以使用go generate命令来生成该文件,但我正在考虑一个合适的名称,以满足以下条件:

  • 显而易见地表明它是生成的,这样如果在构建过程中缺少该文件,用户就会知道需要运行go generate命令。
  • 我可以将该文件添加到.gitignore中。

我第一个猜测是version_GENERATED.go这样的名称。

有没有我应该了解的约定规范,或者更好的建议?

英文:

I'm generating a Go file (to include constants such as build version etc) so that the constants can be used in other packages. I have a created a small tool that will create the file with go generate but am trying to think of an appropriate name so that

  • It is obvious that it is generated, so if it is missing (on build) the user then knows to run go generate

  • And I can then add the file to the .gitignore

My first guess is something like version_GENERATED.go

Any conventions I should be aware of or better suggestions?

答案1

得分: 4

将文件名添加类似_GENERATED这样的后缀并不包含任何信息,直到文件被生成,因为编译器只会给出"无关的"错误,比如"undefined: xxx"(编译器不会猜测如果标识符存在的话,它会在version_GENERATED.go中)。例如,stringer生成器会生成名为type_string.go的文件,其中的type会被替换为它所生成的类型的名称。

所以我认为,遵循文件名的通用准则就足够了,除非可能使用_gen_generated后缀。或者,如果你的工具是公开的并且被其他人使用,那么可以使用工具的名称作为后缀(就像stringer一样)。

如果你确实希望用户在生成器尚未运行时得到一个健谈的错误消息,你的生成器可以生成一个导出的常量,其名称在错误消息中是健谈的,例如:

const MustRunStringerGenerator = 0

然后在你的程序中引用它,例如:

var _ = MustRunStringerGenerator // 检查是否已运行stringer

如果stringer尚未运行,你将看到一个错误消息:

undefined: MustRunStringerGenerator
英文:

Having a suffix like _GENERATED added to the file name does not hold any information until the file is generated, as the compiler will just give you "unrelated" errors like "undefined: xxx" (the compiler won't guess that if the identifier would exists, it would be in version_GENERATED.go).

For example the stringer generator generates files with name type_string.go where type is replaced with the name of the type it is generated for.

So I think simply following the general guidelines for file names is enough, except maybe use _gen or _generated suffix. Or if your tool is public and used by others too, then use the name of the tool as the suffix (like stringer does).

If you do want the user to get a talkative error message in case your generator is yet to be run, your generator may generate an exported constant whose name is talkative if included in an error message, like:

const MustRunStringerGenerator = 0

And in your program refer to it like:

var _ = MustRunStringerGenerator // Test if stringer has been run

If stringer has not yet been run, you'll see an error message:

undefined: MustRunStringerGenerator

huangapple
  • 本文由 发表于 2016年4月27日 20:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/36890166.html
匿名

发表评论

匿名网友

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

确定