Home  >  Article  >  Backend Development  >  Using LDFLAGS to initialize non-basic type variables in GoLang

Using LDFLAGS to initialize non-basic type variables in GoLang

王林
王林forward
2024-02-11 20:36:08341browse

在 GoLang 中使用 LDFLAGS 初始化非基本类型变量

GoLang is a powerful programming language with a unique initialization method when dealing with non-basic type variables. This article will introduce how to use LDFLAGS to initialize non-basic type variables in GoLang. LDFLAGS is a parameter of the Go compiler and can be passed by setting environment variables. With LDFLAGS, we can provide default values ​​for non-basic type variables at compile time, thus simplifying code logic and improving development efficiency. Next, let us take a look at the specific implementation method.

Question content

I am trying to initialize a variable at build time using the ldflags option in go build.

This code works fine:

var version

func printVersion() {
    fmt.Printf(version) // prints the corresponding value
}
<code>go build -ldflags="-X $(ROOT)/pkg/info.version=123"
</code>

But I can't seem to find a way to initialize the variables of my own defined structure. I mean, this doesn't seem to work:

type VersionInfo struct {
    version string
}

var versionInfo VersionInfo

func printVersion() {
    fmt.Printf(versionInfo.version)
}
<code>go build -ldflags="-X $(ROOT)/pkg/info.versionInfo.version=123"
</code>

I can't find anything covering this issue in the official documentation. Any ideas?

Workaround

According to the documentation, it seems it is not possible to do this via linker flags. The variable must be of type string.

Source: https://www.php.cn/link/0a97e4f47718632c556e9ac591d5f3c2 p>

The above is the detailed content of Using LDFLAGS to initialize non-basic type variables in GoLang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete