go generate用法
1.generate命令
$ go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]
//添加注釋
//go:generate command argument... //注意:雙斜線之后沒有空格
2.使用 go generate 工具編譯 protobuf
//go:generate protoc --go_out=. *.proto
package test
或者
//go:generate sh -c "protoc --go_out=. *.proto"
package test
說明:這里stringer需要手動安裝
go get golang.org/x/tools/cmd/stringer
或者:
$ git clone https://github.com/golang/tools/ $GOPATH/src/golang.org/x/tools
$ go install golang.org/x/tools/cmd/stringer
3.自動生成 Stringer 接口
package painkiller
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
func (p Pill) String() string {
switch p {
case Placebo:
return "Placebo"
case Aspirin:
return "Aspirin"
case Ibuprofen:
return "Ibuprofen"
case Paracetamol: // == Acetaminophen
return "Paracetamol"
}
return fmt.Sprintf("Pill(%d)", p)
}
=============================================
//go:generate stringer -type=Pill
package painkiller
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
==============================================
// 自動生成 pill_string.go
// generated by stringer -type Pill pill.go; DO NOT EDIT
package painkiller
import "fmt"
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
if i < 0 || i+1 >= Pill(len(_Pill_index)) {
return fmt.Sprintf("Pill(%d)", i)
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
4.Error錯誤的處理
(1.)傳統的錯誤處理,通過map返回
package errcode
import "fmt"
// 定義錯誤碼
const (
ERR_CODE_OK = 0 // OK
ERR_CODE_INVALID_PARAMS = 1 // 無效參數
ERR_CODE_TIMEOUT = 2 // 超時
// ...
)
// 定義錯誤碼與描述信息的映射
var mapErrDesc = map[int]string {
ERR_CODE_OK: "OK",
ERR_CODE_INVALID_PARAMS: "無效參數",
ERR_CODE_TIMEOUT: "超時",
// ...
}
// 根據錯誤碼返回描述信息
func GetDescription(errCode int) string {
if desc, exist := mapErrDesc[errCode]; exist {
return desc
}
return fmt.Sprintf("error code: %d", errCode)
}
(2.)使用string()方法實現
// ErrCode used to define response code
type ErrCode uint32
//go:generate stringer -type ErrCode -output code_string.go
或者//go:generate stringer -type ErrCode -linecomment -output code_string.go
const (
ERR_CODE_OK ErrCode = 0 // OK
ERR_CODE_INVALID_PARAMS ErrCode = 1 // 無效參數
ERR_CODE_TIMEOUT ErrCode = 2 // 超時
)
//注意:執行go generate 會在同一個目錄下生成一個文件errcode_string.go
func (i ErrCode) String() string {
// xxx
}
//為了防止忘記手動generate,可以寫到makefile中
all:
go generate && go build .
go-swag:
swag init --parseVendor -g ./main.go
5.其他用法
package main
import "fmt"
//go:generate echo GoGoGo!
//go:generate go run main.go
//go:generate echo $GOARCH $GOOS $GOFILE $GOLINE $GOPACKAGE
func main() {
fmt.Println("go rum main.go!")
}
相關鏈接
http://c.biancheng.net/view/4442.html
https://www.xiaoheidiannao.com/70045.html
https://juejin.cn/post/6844903923166216200
https://islishude.github.io/blog/2019/01/23/golang/go-generate-預處理器教程/