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
+46.6k Golang : Encode image to base64 example
+7.7k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+16.6k Golang : Send email and SMTP configuration example
+5.1k Python : Convert(cast) bytes to string example
+11k Golang : How to transmit update file to client by HTTP request example
+20.5k Golang : Check if os.Stdin input data is piped or from terminal
+6.4k Golang : Calculate US Dollar Index (DXY)
+6.1k Golang : Extract unicode string from another unicode string example
+7.3k Golang : Dealing with postal or zip code example
+9.3k Golang : Serving HTTP and Websocket from different ports in a program example
+16.5k Golang : Loop each day of the current month example
+10.7k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery