简体   繁体   English

如何在 Go 中实现宏?

[英]how to implement macros in Go?

I've project done in C++ where I used #define macros to give a name of the project, which I used in several places, I don't change this name often but sometimes I may need to change this, then I change this macro and rebuild my code.我在 C++ 中完成了项目,我使用#define宏给项目命名,我在几个地方使用过,我不经常更改此名称,但有时我可能需要更改此名称,然后我更改此宏并重建我的代码。 Now I'm converting this code to Go.现在我正在将此代码转换为 Go。 Can someone suggest me how to implement this in Go?有人可以建议我如何在 Go 中实现它吗? I'm not interested in using global variables for this purpose because I've many such macros and I doubt this cause my project to occupy more cpu and effect the performance.我对为此目的使用全局变量不感兴趣,因为我有很多这样的宏,我怀疑这会导致我的项目占用更多 cpu 并影响性能。

Luckily, Go does not support macros.幸运的是,Go 不支持宏。

There are two venues in Go to implement what is done using macros in other programming languages: Go 中有两个地方可以实现使用其他编程语言中的宏所做的事情:

  • "Meta-programming" is done using code generation . “元编程”是使用代码生成完成的。
  • "Magic variables/constants" are implemented using "symbol substitutions" at link time. “魔术变量/常量”在链接时使用“符号替换”实现。

It appears, the latter is what you're after.看来,后者才是你所追求的。

Unfortunately, the help on this feature is nearly undiscoverable on itself, but it explained in the output of不幸的是,此功能的帮助本身几乎无法发现,但它在输出中进行了解释

$ go tool link -help

To cite the relevant bit from it:从中引用相关位:

-X definition

add string value definition of the form importpath.name=value添加表单importpath.name=value字符串值definition

So you roll like this:所以你像这样滚动:

  1. In any package, where it is convenient, you define a string constant the value of which you'd like to change at build time.在任何方便的包中,您可以定义一个字符串常量,您希望在构建时更改其值。

    Let's say, you define constant Bar in package foo .假设您在包foo定义了常量Bar

  2. You pass a special flag to the go build or go install invocation for the linking phase at compile time:您可以在编译时为链接阶段的go buildgo install调用传递一个特殊标志:

     $ go install -ldflags='-X foo.Bar="my super cool string"'

As the result, the produced binary will have the constant foo.Bar set to the value "my super cool string" in its "read-only data" segment, and that value will be used by the program's code.结果,生成的二进制文件将在其“只读数据”段中将常量foo.Bar设置为值“我的超酷字符串”,该值将被程序代码使用。

See also the go help build output about the -ldflags option.另请参阅有关-ldflags选项的go help build输出。

Go doesn't support Macros . Go 不支持Macros
but you can use a constants inside a package and refer it where ever you need.但是您可以在包中使用常量并在需要时引用它。

package constant
// constants.go file

const (
    ProjectName = "My Project"
    Title       = "Awesome Title"
)

and in your program在你的程序中

package main
import "<path to project>/constant" // replace the path to project with your path from GOPATH

func main() {
     fmt.Println(constant.ProjectName)
}

The project structure would be项目结构将是

project
   |- constant
   |      |- constants.go
   |-main.go

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM