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
+5.6k Golang : PGX CopyFrom to insert rows into Postgres database
+12.3k Golang : md5 hash of a string
+6.9k Golang : Find the longest line of text example
+26.4k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+19.7k Golang : Example for DSA(Digital Signature Algorithm) package functions
+8.9k Golang : Heap sort example
+5.3k Golang : Experimental Jawi programming language
+7.7k Android Studio : How to detect camera, activate and capture example
+8.1k Golang Hello World Example
+11.8k Golang : Simple file scaning and remove virus example
+6.3k Golang : Get missing location after unmarshal binary and gob decode time.
+6.4k Golang : Extract sub-strings