Golang : Setting variable value with ldflags
This short tutorial will demonstrate how to initialize a variable value during runtime at the stage of compilation/linking. Go linker has an option to set the value of an uninitialised string variable:
-X symbol value
Set the value of an otherwise uninitialized string variable.
The symbol name should be of the form importpath.name,
as displayed in the symbol table printed by "go tool nm".
For example :
package main
import "fmt"
var str string
func main() {
fmt.Println(str)
}
and execute the program with -ldflags
to initialize the str variable value
$ go run -ldflags "-X main.str abc" main.go
or if you prefer, build it first into executable binary :
$ go build -ldflags "-X main.str 'abc'" main.go && ./main
Output :
abc
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.4k Golang : Handling Yes No Quit query input
+8.2k Golang : Number guessing game with user input verification example
+5.1k PHP : See installed compiled-in-modules
+16.3k Golang : Convert slice to array
+8.2k Golang : Emulate NumPy way of creating matrix example
+5.5k Golang : Detect words using using consecutive letters in a given string
+10.1k Golang : Bcrypting password
+11.4k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+23.7k Golang : Fix type interface{} has no field or no methods and type assertions example
+7.8k Setting $GOPATH environment variable for Unix/Linux and Windows
+14.5k Golang : Convert(cast) int to float example
+21.6k SSL : How to check if current certificate is sha1 or sha2