如何在 Go 中实现宏? [英] how to implement macros in Go?
问题描述
我在 C++ 中完成了项目,我使用 #define
宏来命名项目,我在几个地方使用过这个名称,我不经常更改这个名称,但有时我可能会需要改变这个,然后我改变这个宏并重建我的代码.现在我正在将此代码转换为 Go.有人可以建议我如何在 Go 中实现这一点吗?我对为此目的使用全局变量不感兴趣,因为我有很多这样的宏,我怀疑这会导致我的项目占用更多的 cpu 并影响性能.
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. Now I'm converting this code to Go. Can someone suggest me how to implement this in 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.
推荐答案
幸运的是,Go 不支持宏.
Luckily, Go does not support macros.
Go 中有两个场所可以实现使用宏完成的工作其他编程语言:
There are two venues in Go to implement what is done using macros in other programming languages:
- 元编程"使用代码生成完成.
- 魔术变量/常量"使用符号替换"来实现.在链接时.
看来,后者正是你所追求的.
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
从中引用相关位:
-X定义
添加 definition
形式的字符串值 importpath.name=value
add string value definition
of the form importpath.name=value
所以你这样滚动:
在任何方便的地方,您定义一个字符串常量,您希望在构建时更改其值.
In any package, where it is convenient, you define a string constant the value of which you'd like to change at build time.
假设你在包foo
中定义了常量Bar
.
Let's say, you define constant Bar
in package foo
.
您将一个特殊标志传递给编译时链接阶段的 go build
或 go install
调用:
You pass a special flag to the go build
or go install
invocation for the linking phase at compile time:
$ go install -ldflags='-X foo.Bar="my super cool string"'
因此,生成的二进制文件将具有常量 foo.Bar
设置为值我的超酷字符串"在其只读数据"中分割,并且该值将被程序的代码使用.
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.
另请参阅关于 -ldflags
选项的 go help build
输出.
See also the go help build
output about the -ldflags
option.
这篇关于如何在 Go 中实现宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!