执行 go generate 命令时,会执行 //go:generate
之后的命令,注意 //
后面没有空格。
//go:generate
可以放在已有代码的任何位置,或者单独新建 go 文件用于各种 //go:generate
指令。
go generate 比较常见的应用是 //go:generate stringer -type=iotaConstTypeName
用于为 iota 类型枚举值生成 String()
方法。
当然,很多时候也会在 //go:generate
之后接 go run 命令,由 go 代码来生成代码,此时可能会涉及到 template,条件编译之类的知识,可以阅读下面的参考链接。
参考资料
How to Use go:generate
https://blog.carlmjohnson.net/post/2016-11-27-how-to-use-go-generate/
Generating code
https://blog.golang.org/generate
Text Generation With Go Templates
https://code.tutsplus.com/tutorials/text-generation-with-go-templates--cms-30441
Package template
https://golang.org/pkg/text/template/
Build Constraints
https://golang.org/pkg/go/build/#hdr-Build_Constraints
How to use conditional compilation with the go build tool
https://dave.cheney.net/2013/10/12/how-to-use-conditional-compilation-with-the-go-build-tool
最后修改于 2019-04-19