英文:
Is there a way to define a constant at build time in Go?
问题
我有一个用Go编写的程序,我想将其编译为一组不同的二进制文件,每个文件中的const
值定义不同。更明确地说,我有类似以下的代码:
const wordLen = 6
type knowledge [wordLen]byte
在这里,wordLen
与值6相关联,但我希望有不同的二进制文件,其值范围从5到10不等。我可以将其改为变量,然后使用切片而不是数组,但这会对我的软件产生巨大的性能影响(是的,我尝试过)。
我希望在go build
命令的构建标签中指示给定二进制文件的wordLen
值。那么,有什么(尽可能符合惯用方式的)方法可以实现这一点呢?
英文:
I have a program in Go that I want to compile in a bunch of binaries, each having a const
value defined differently. More clearly, I have something like that:
const wordLen = 6
type knowledge [wordLen]byte
Here, wordLen
is associated with the value 6, but I want to have different binaries, with values ranging from 5 to 10. I could make it a variable, and then use a slice rather than an array, but that would have a huge performance impact on my soft (yes, I tried).
I would love to have some build tag on go build
argument to indicate what the value of wordLen
is for a given binary. So, what is the (as idiomatic as possible) way to do this ?
答案1
得分: 21
是的,可以使用构建约束来实现这一点。
您可以使用-tags
标志向go build
提供一系列约束条件。
示例:
main.go
package main
import "fmt"
func main() {
fmt.Println(f)
}
foo.go
// +build foo
package main
const f = "defined in foo.go"
bar.go
// +build bar
package main
const f = "defined in bar.go"
使用不同的标签编译代码将得到不同的结果:
<!-- language: bash -->
$ go build -tags foo
$ ./main
defined in foo.go
$ go build -tags bar
$ ./main
defined in bar.go
英文:
Yes, this is possible using Build Constraints.
You can supply a list of these constraints to go build
using the -tags
flag.
Example:
main.go
package main
import "fmt"
func main() {
fmt.Println(f)
}
foo.go
// +build foo
package main
const f = "defined in foo.go"
bar.go
// +build bar
package main
const f = "defined in bar.go"
Compiling the code with different tags will give different results:
<!-- language: bash -->
$ go build -tags foo
$ ./main
defined in foo.go
$ go build -tags bar
$ ./main
defined in bar.go
答案2
得分: 12
这不会解决你的确切问题,但可能会解决其他问题,所以我为了完整性而添加了一个方法,你可以使用go编译器的-ldflags
选项:
go build -ldflags "-X main.wordLen=6"
然而,它有两个缺点:
- 只适用于字符串
- 只适用于变量
英文:
It doesn't solve your exact problem but it may solve others so I add for compelteness that you can use the -ldflags
option of the go compiler:
go build -ldflags "-X main.wordLen=6"
Its however has two downsides:
- Only works for strings
- Only works on vars
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论