如何在编译时定义常量

I know that I can use compiler flag in Go for variables, but how to do it for constants?

I would like to set some constants, like database sets, at compile time like that:

package db_info

var Deploy string

const DbType   = "mysql"
const DbUser   = "my_user"
const Db       = "my_db"
const DbPort   = "3306"

if Deploy == "staging" {
    const DbPassword = "my_pwd_stg"
    const DbHost     = "db.url.com"
} else if Deploy == "production" {
    const DbPassword = "my_pwd_prd"
    const DbHost     = "db.url.com"
} else {
    const DbPassword = "pwd"
    const DbHost     = "127.0.0.1"
}

How to do it in correctly? Like that I got:

syntax error: non-declaration statement outside function body

You cannot do that. It would break the scoping rules. You would expect the constants to be globally visible but they are defined within a block.


I would just pass those values as program parameters or environment variables.


On the other hand, as you mentioned, you can modify string variables at the compilation time. Use -ldflags to do it.

go run -ldflags="-X main.who=Something" hello.go

in

package main

import "fmt"

var who = "World"

func main() {
    fmt.Printf("Hello, %s.
", who)
}

See https://blog.cloudflare.com/setting-go-variables-at-compile-time/