How to properly use build tags?

后端 未结 2 1381
甜味超标
甜味超标 2021-02-01 03:56

I need to be able to build different versions of a go application; a \'debug\' version and a normal version.

This is easy to do; I simply have a const DEBUG, that contro

2条回答
  •  独厮守ぢ
    2021-02-01 04:44

    You could use compile time constants for that: If you compile your program with

    go build -ldflags '-X main.DEBUG=YES' test.go
    

    the variable DEBUG from package main will be set to the string "YES". Otherwise it keeps its declared contents.

    package main
    
    import (
        "fmt"
    )
    
    var DEBUG = "NO"
    
    func main() {
        fmt.Printf("DEBUG is %q\n", DEBUG)
    }
    

    Edit: since Go 1.6(?) the switch is -X main.DEBUG=YES, before that it was -X main.DEBUG YES (without the =). Thanks to a comment from @poorva.

提交回复
热议问题