skip to content
Alvin Lucillo

Inject variable value at build time

/ 1 min read

You can use linker flags to inject values during build. This is useful if your Go program references dynamic value related to build environment such as build version, commit hash, or environment information.

For example, if you run go run . on the program below, it outputs Hello, Duo.

But when you build it with go build -ldflags "-X main.name=Julia" and run the binary, it outputs: Hello, Julia.

The build command references the package name main and the variable name.

package main

import "fmt"

var name = "Duo"

func main() {
	fmt.Printf("Hello, %v", name)
}