Inject build-time values like version numbers into Go binaries using the -ldflags -X command line option.
Use the -ldflags flag with the -X option to set package variables at link time. Define a variable in your code (e.g., var Version string) and pass the assignment via the command line.
go build -ldflags "-X main.Version=1.0.0" -o myapp main.go
In main.go, declare the variable to receive the value:
package main
var Version string
func main() {
println(Version)
}
Using ldflags lets you embed specific data, like a version number or build timestamp, directly into your program while it is being compiled. Think of it like stamping a date on a product before it leaves the factory; the information is permanently part of the final file. You use this to avoid hardcoding values in your source code, making it easier to manage releases.