Problem:
When building a Go application, is it feasible to assign a version string variable to a package other than the main package using the -ldflags -X options?
Solution:
Yes, it is possible to set a variable in any package using -ldflags -X. However, it requires specifying the full import path of the package, not just the package name.
To achieve this, use the following syntax:
-X importpath.package.variable=value
For example, if the config package is located at $GOPATH/src/my/package/config, use the following build command:
go build -ldflags "-X my/package/config.Version=1.0.0" -o $(MY_BIN) $(MY_SRC)
This command will assign the value 1.0.0 to the Version variable in the config package.
The above is the detailed content of Can Go's `-ldflags -X` Assign Variables to Packages Other Than `main`?. For more information, please follow other related articles on the PHP Chinese website!