如何使用go build -ldflags在编译时设置布尔变量

Kok*_*zzu 5 ld go

我有一个去计划 test.go

package main

import "fmt"

var DEBUG_MODE bool = true    

func main() {
  fmt.Println(DEBUG_MODE)
}
Run Code Online (Sandbox Code Playgroud)

我想DEBUG_MODE编译时将变量设置为false

我试过了:

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                                                                               
Run Code Online (Sandbox Code Playgroud)

它不起作用,但是当它DEBUG_MODE是一个时它起作用string

Ain*_*r-G 5

您只能使用-X链接器标志设置字符串变量.来自文档:

-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.
Run Code Online (Sandbox Code Playgroud)

您可以改用字符串:

var DebugMode = "true"
Run Code Online (Sandbox Code Playgroud)

然后

go build -ldflags "-X main.DebugMode=false" test.go && ./test
Run Code Online (Sandbox Code Playgroud)