简体   繁体   English

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

[英]How to set boolean variable on compile time using go build -ldflags

I have a go program test.go 我有一个go程序test.go

package main

import "fmt"

var DEBUG_MODE bool = true    

func main() {
  fmt.Println(DEBUG_MODE)
}

I want to set the DEBUG_MODE variable on the compile time to false 我想在编译时将DEBUG_MODE变量设置为false

I've 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                                                                               

It doesn't work, but it works when DEBUG_MODE is a string 它不起作用,但是当DEBUG_MODE是一个string时它起作用

You can only set string variables with -X linker flag. 您只能使用-X链接器标志设置字符串变量。 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.

You can use a string instead: 您可以改用字符串:

var DebugMode = "true"

and then 然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM