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
+29.3k Golang : JQuery AJAX post data to server and send data back to client example
+33.5k Golang : How to check if slice or array is empty?
+9.7k Golang : Load ASN1 encoded DSA public key PEM file example
+9.8k Golang : Sort and reverse sort a slice of integers
+18.9k Golang : Padding data for encryption and un-padding data for decryption
+15.1k Golang : Save(pipe) HTTP response into a file
+6.8k Swift : substringWithRange() function example
+29.4k Golang : How to create new XML file ?
+11.5k Android Studio : Create custom icons for your application example
+19.2k Golang : Get RGBA values of each image pixel
+8.4k PHP : How to parse ElasticSearch JSON ?
+17.5k Golang : Clone with pointer and modify value