如何在模块中忽略一个.go文件?

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

How to ignore a .go file in a module?

问题

我正在用Go语言重写之前用Python编写的一个家庭级程序,并在学习的过程中逐步改进。在重新考虑代码的整个部分时,如果我能够忽略一些我编写的.go文件就太好了(它们会引发编译错误,但这没关系,因为它们与我对该问题的最新方法不同步)。

我可以将它们移出目录,或者重命名它们,但我想知道是否有一种更符合惯用方式的方法来忽略模块目录中的一些.go文件?

英文:

I am rewriting in Go a home-grade program of mine that was previously in Python, learning on the way. As I reconsider whole sections of the code, it would be great if I could ignore some .go files I wrote (they throw compilation errors which is OK as they are not synchronized with my latest approach to the problem).

I could move them out of the directory, or rename them but I was wondering whether there would be a more idiomatic way to ignore some .go files in a module directory?

答案1

得分: 24

构建标签完全适合您的用例。

构建约束,也称为构建标签,用于在构建过程中包含或排除软件包中的文件。通过这种方式,我们可以从相同的源代码构建不同类型的构建。

因此,如果您想从构建过程中排除某个文件,请为其指定不同的构建标签。例如,如果您在文件顶部使用//go:build exclude,在执行go build时,该文件将不会被包含在内。注意,exclude可以是任何单词。

有关构建标签的更多详细信息,请参阅Dave Cheney的以下文章这里

TLDR

> 在要忽略的文件顶部添加
>
> //go:build exclude 适用于 go v1.17 及以上版本
>
> //+build exclude 适用于 go v1.17 及以下版本

英文:

Build tags fit perfectly to your use case.

A Build Constraint or also known as Build Tag is used to include or exclude files in a package during a build process. With this, we can build different types of builds from the same source code.

So if you want to exclude a file from the build process, give it a different Build Tag. For example if you use //go:build exclude at the top of the file when you perform go build it won't be included. Note that exclude can be any word.

For more details on the Build Tags check out the following article by Dave Cheney here

TLDR

> Add
>
> //go:build exclude for go v1.17 and above
>
> //+build exclude for go v1.17 and below

to the top of the file you wish to ignore.

huangapple
  • 本文由 发表于 2021年5月22日 22:34:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/67650677.html
匿名

发表评论

匿名网友

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

确定