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
+12.4k Golang : zlib compress file example
+11.8k Golang : convert(cast) string to integer value
+20.8k Golang : Create and resolve(read) symbolic links
+9.7k Golang : Get escape characters \u form from unicode characters
+7.9k Golang : HttpRouter multiplexer routing example
+5.8k Golang : Compound interest over time example
+14.1k Golang : How to filter a map's elements for faster lookup
+13.9k Golang : syscall.Socket example
+6.9k Nginx : How to block user agent ?
+11.2k Swift : Convert (cast) Float to String
+6.5k How to let Facebook Login button redirect to a particular URL ?
+21k Golang : How to read float value from standard input ?