Feb 25, 2019

[Go] build tag constraint useful for conditional const variable

Reference:
Is there a way to define a constant at build time in Go?
Go Build Constraints

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

This trick also useful under 'go test'
$ go test -tags=foo

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.