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
+21.3k Golang : Get password from console input without echo or masked
+7.2k Golang : Validate credit card example
+6k Golang : Generate multiplication table from an integer example
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.5k Golang : How to detect if a sentence ends with a punctuation?
+8.2k Golang : Append and add item in slice
+18.5k Golang : Read binary file into memory
+9.2k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+9.9k Golang : List available AWS regions
+6.2k Golang : Create new color from command line parameters
+5.3k Golang : Customize scanner.Scanner to treat dash as part of identifier
+19.4k Golang : Display list of time zones with GMT