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
+8k Golang : How to convert a number to words
+3.6k Golang : Struct field tags and what is their purpose?
+2.3k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+8.7k Golang : Handle or parse date string with Z suffix(RFC3339) example
+23.5k Golang : Regular Expression for alphanumeric and underscore
+3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+5.7k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+5.6k Golang : Extract or copy items from map based on value
+7k JavaScript/JQuery : Detect or intercept enter key pressed example
+27.4k Golang : How do I convert int to uint8?
+6.1k Golang : ffmpeg with os/exec.Command() returns non-zero status
+15.4k Golang : Convert date string to variants of time.Time type examples