How to set a boolean variable at compile time with go build -ldflags

I have a go test.go

 package main import "fmt" var DEBUG_MODE bool = true func main() { fmt.Println(DEBUG_MODE) } 

I want to set DEBUG_MODE variable to compile time false

I tried:

 go build -ldflags "-X main.DEBUG_MODE 0" test.go && ./test true kyz@s497 :18:49:32:/tmp$ go build -ldflags "-X main.DEBUG_MODE false" test.go && ./test true kyz@s497 :18:49:41:/tmp$ go build -ldflags "-X main.DEBUG_MODE 0x000000000000" test.go && ./test true 

This does not work, but it works when DEBUG_MODE is a string

+5
source share
1 answer

You can only set string variables with the -X flag. From the docs :

 -X importpath.name=value Set the value of the string variable in importpath named name to value. Note that before Go 1.5 this option took two separate arguments. Now it takes one argument split on the first = sign. 

Instead, you can use the line:

 var DebugMode = "true" 

and then

 go build -ldflags "-X main.DebugMode=false" test.go && ./test 
+5
source

Source: https://habr.com/ru/post/1208227/


All Articles