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
+19.7k Golang : How to read float value from standard input ?
+11.4k Golang : Covert map/slice/array to JSON or XML format
+13.3k Golang : How to shuffle elements in array or slice?
+5.9k How to let Facebook Login button redirect to a particular URL ?
+17.1k Golang : How to get hour, minute, second from time?
+6.2k Golang : Example of custom handler for Gorilla's Path usage.
+7.4k Golang : Convert word to its plural form example
+20.6k Golang : Match strings by wildcard patterns with filepath.Match() function
+3.3k Javascript : Empty an array example
+22.9k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+25.5k Golang : dial tcp: too many colons in address
+8.3k Golang : Read file with ioutil