Golang预处理器类似于C风格的编译开关。

huangapple go评论72阅读模式
英文:

Golang Preprocessor like C-style compile switch

问题

GO语言有预处理器吗?当我在互联网上查找时,有一些方法可以将*.pgo转换为*.go。而且,我想知道在Go语言中是否可行。

#ifdef COMPILE_OPTION
{编译这段代码...}
#elif
{编译另一段代码...}

或者,
#undef in c

英文:

Does GO language have a preprocessor? When I looked up internet, there was few approaches which *.pgo convert to *.go. And, I wonder if it is doable in Go

#ifdef COMPILE_OPTION
  {compile this code ... }
#elif 
  {compile another code ...}

or,
#undef in c

答案1

得分: 39

最接近实现这一目标的方法是使用构建约束。示例:

main.go

package main

func main() {
	println("main()")
	conditionalFunction()
}

a.go

// +build COMPILE_OPTION

package main

func conditionalFunction() {
	println("conditionalFunction")
}

b.go

// +build !COMPILE_OPTION

package main

func conditionalFunction() {
}

输出:

% go build -o example ; ./example
main()

% go build -o example -tags COMPILE_OPTION ; ./example
main()
conditionalFunction
英文:

The closest way to achieve this is by using build constraints. Example:

main.go

package main

func main() {
	println("main()")
	conditionalFunction()
}

a.go

// +build COMPILE_OPTION

package main

func conditionalFunction() {
	println("conditionalFunction")
}

b.go

// +build !COMPILE_OPTION

package main

func conditionalFunction() {
}

Output:

% go build -o example ; ./example
main()

% go build -o example -tags COMPILE_OPTION ; ./example
main()
conditionalFunction

答案2

得分: 2

潜在地,可以使用Java Comment Preprocessor + maven golang plugin来实现类似的行为,这样的话,Golang代码会像这样:

//#if COMPILE_OPTION
 fmt.Println("Ok")
//#else
 fmt.Println("No")
//#endif

这里有一些示例放在了这个链接中:https://github.com/raydac/mvn-golang/tree/master/mvn-golang-examples/mvn-golang-examples-preprocessing

英文:

potentially it is possible to use Java Comment Preprocessor + maven golang plugin and get some similar behavior, in the case golang code will look like

//#if COMPILE_OPTION
 fmt.Println("Ok")
//#else
 fmt.Println("No")
//#endif

some example has been placed here https://github.com/raydac/mvn-golang/tree/master/mvn-golang-examples/mvn-golang-examples-preprocessing

答案3

得分: 2

请注意,可以使用任何宏语言作为Go的预处理器。一个例子是GNU的m4宏语言。

然后,您可以在*.go.m4文件中编写代码,使用构建系统将它们通过m4转换为生成的*.go文件,然后进行编译。

这对于编写泛型代码也很方便。

英文:

Note that it's possible to use any macro language as a preprocessor for go. An example would be GNU's m4 macro language.

You can then write your code in *.go.m4 files, use your build system to feed them through m4 to turn them into generated *.go files, and then compile them.

This can also be handy for writing generics.

huangapple
  • 本文由 发表于 2016年4月19日 04:39:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36703867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定