Can Go linker overrides initialized variables

From ld docs :

-X character value

Set the value of the uninitialized string variable differently. The symbol name should be importpath.name, as shown in the symbol table printed by "go tool nm".

So it's pretty cool. This allows you to do things like this:

package main

import "fmt"

var version string

func main() {
    fmt.Println(version)
}

Compile with: go build -ldflags '-X main.version 42' ...

I have two questions about its function. First of all, it also works for initialized strings (for example, var version = "bad build"), although the documentation specifically says "an otherwise uninitialized string variable".

The question of seconds is spaces. My Makefilecontains the following lines:

GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null)
GIT_COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null)

LDFLAGS := '-X main.version "$(GIT_BRANCH) $(GIT_COMMIT)"'

The documentation for the team gosays:

-ldflags 'flag list'

, . , -X? , . , , , , .

:

Go zero vars.

: -X symbol value Set the value of an otherwise uninitialized string variable [...].

:

var foo string // only this one?
var bar = "bar" // or this one too, maybe
+4
1

( make), , .

go args.

//

, - :

var version string

func init() {
    if len(version) == 0 {
        version = "master"
    }
}

//edit 2

spec:

, make , , . : false booleans, 0 , 0.0 float, "" nil , , , , .

+2

All Articles