Is there a way to define a constant during build in Go?

I have a program in Go that I want to compile into a bunch of binaries, each of which has a const value, defined differently. More clearly, I have something like this:

 const wordLen = 6 type knowledge [wordLen]byte 

Here wordLen is associated with a value of 6, but I want to have different binaries with values ​​from 5 to 10. I could make it a variable and then use a slice rather than an array, but that will have a huge impact on my softness (yes, I tried )

I would like to have some kind of build tag on the go build argument to indicate that the wordLen value wordLen for this binary. So what is the way (as idiomatic as possible) to do this?

+6
source share
2 answers

Yes, this is possible with Build Constraints .

You can provide a list of these go build restrictions 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 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 
+9
source

It does not solve your exact problem, but it can solve others, so I add for completeness that you can use the -ldflags option of the -ldflags compiler:

 go build -ldflags "-X main.wordLen=6" 

However, it has two drawbacks:

  • Only works for strings.
  • Only works with vars
+4
source

All Articles