Using LDFLAGS to initialize non-basic type variables in GoLang

王林
Release: 2024-02-11 20:36:08
forward
372 people have browsed it

在 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
}
Copy after login
<code>go build -ldflags="-X $(ROOT)/pkg/info.version=123"
</code>
Copy after login

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)
}
Copy after login
<code>go build -ldflags="-X $(ROOT)/pkg/info.versionInfo.version=123"
</code>
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!