go generate 生成代码
简单使用 ,通过注释生成代码
1go install golang.org/x/tools/cmd/stringer@v0.6.0
2cd /Users/maozhongyu/code/go-tool/generate/code
3go generate .
1//go:generate stringer -type ErrCode -linecomment
2package code
3
4type ErrCode int64 //错误码
5
6// 错误码
7const (
8 ERR_CODE_OK ErrCode = 0 //ok
9 ERR_CODE_INVALID_PARAMS ErrCode = 1 //参数错误
10 ERR_CODE_TIMEOUT ErrCode = 2 //超时
11)
生成的代码
1
2// Code generated by "stringer -type ErrCode -linecomment"; DO NOT EDIT.
3
4package code
5
6import "strconv"
7
8func _() {
9 // An "invalid array index" compiler error signifies that the constant values have changed.
10 // Re-run the stringer command to generate them again.
11 var x [1]struct{}
12 _ = x[ERR_CODE_OK-0]
13 _ = x[ERR_CODE_INVALID_PARAMS-1]
14 _ = x[ERR_CODE_TIMEOUT-2]
15}
16
17const _ErrCode_name = "ok参数错误超时"
18
19var _ErrCode_index = [...]uint8{0, 2, 14, 20}
20
21func (i ErrCode) String() string {
22 if i < 0 || i >= ErrCode(len(_ErrCode_index)-1) {
23 return "ErrCode(" + strconv.FormatInt(int64(i), 10) + ")"
24 }
25 return _ErrCode_name[_ErrCode_index[i]:_ErrCode_index[i+1]]
26}
ast 语法树
在线解析网站 : https://astexplorer.net/
https://cs.opensource.google/go/x/tools/+/refs/tags/v0.17.0:cmd/stringer/stringer.go
mongo dao生成案例 : https://github.com/cr-mao/mongo-dao-generator
模仿这干。