Is there a way to define a constant at build time in Go?

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

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 &quot;fmt&quot;

func main() {
    fmt.Println(f)
}

foo.go

// +build foo

package main

const f = &quot;defined in foo.go&quot;

bar.go

// +build bar

package main

const f = &quot;defined in bar.go&quot;

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 &quot;-X main.wordLen=6&quot;

Its however has two downsides:

  • Only works for strings
  • Only works on vars

huangapple
  • 本文由 发表于 2016年3月22日 18:02:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/36151298.html
匿名

发表评论

匿名网友

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

确定