go build命令的-ldflags选项可以在编译时修改go源代码里的常量的值

// main.go文件
package main

import "fmt"

const isDebug = false  // 默认 false;可以在构建脚本中用 -ldflags 修改

func main() {
    if isDebug {
        fmt.Println("DEBUG: This is a test message")
    }
}

构建时用-ldflags "-X main.isDebug=true"来设置isDebug常量的值(链接时注入):

go build -ldflags "-X main.isDebug=true" -o main.exe

类似于C/C++在编译源代码时使用-D选项设置宏标志或某个宏的值。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注