英文:
Do const if statements do the same thing as #ifdef macros in Go?
问题
在Go语言中没有文本预处理。与Java和其他类似的语言一样,如果我想删除一段代码,我可以使用一个const
值,并用一个if
语句将代码包围起来。
如果我这样做,编译器会从AST(抽象语法树)中优化代码并生成优化后的代码吗?还是条件每次都会被执行?
编辑:如果我想复制#ifdef
的功能,最好的方法是什么?
英文:
There's no text preprocessing in Go. Like Java and others like it, if I want to remove a block of code I can use a const
value and surround the code with an if
.
If I do this, does the compiler optimise the code from the AST and out of the generated code? Or is the condition executed each time?
EDIT: If I want to replicate #ifdef
what's the best way to do it?
答案1
得分: 9
如果语句中的条件是常量,那么与#ifdef
不同,因为无论如何都会编译其中的代码。然而,编译器会在可能的情况下进行优化。考虑以下程序:
package main
import (
"fmt"
)
func main() {
if false {
fmt.Println("Hello, world!")
}
}
如果我们运行go tool 6g -S test.go
,这是main
函数的汇编输出:
--- prog list "main" ---
0000 (test.go:7) TEXT main+0(SB),$40-0
0001 (test.go:11) RET ,
无用的代码已经消失,所以它只是返回。
如果您确实需要有条件地编译代码的一部分,最好通过构建系统来实现。
英文:
If statements with constant conditions are not the same as #ifdef
because the code inside is always compiled no matter what. However, the compilers do optimize it away when possible. Consider this program:
package main
import (
"fmt"
)
func main() {
if false {
fmt.Println("Hello, world!")
}
}
If we run go tool 6g -S test.go
, here's the assembly output for the main
function:
--- prog list "main" ---
0000 (test.go:7) TEXT main+0(SB),$40-0
0001 (test.go:11) RET ,
The dead code is gone so all it does is return.
If you do need to actually conditionally compile parts of your code, it's best to do it through the build system.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论