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
+16k Golang : Find biggest/largest number in array
+1.5k Golang : Mapping Iban to Dunging alphabets
+10.5k Golang : Simple client server example
+4.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+6.7k Golang : Validate hostname
+2.6k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+1k Golang : Calculate a pip value and distance to target profit example
+2.6k Unix/Linux : secure copying between servers with SCP command examples
+2.3k Golang : How to verify input is rune?
+3.2k Golang : Get environment variable
+2.8k Golang : How to determine if request or crawl is from Google robots
+5.9k Golang : Recombine chunked files example