Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 674
Fabien Avatar asked Mar 22 '16 10:03

Fabien


1 Answers

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:

$ go build -tags foo
$ ./main
defined in foo.go
$ go build -tags bar
$ ./main
defined in bar.go
like image 151
nemo Avatar answered Sep 18 '22 17:09

nemo