#青训营 x 字节后端训练营# day19Go工具之generate

Go工具之generate
本文给大家介绍Go的一个实用技巧,该技巧主要通过go工具实现。

传统写法
大家经常碰到命名错误码、状态码的同时,又要同步写码对应的翻译,有没有感觉很无聊。这里举一个例子:

package main

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)
}

func main() {
fmt.Println(GetDescription(ERR_CODE_OK))
}
这是一种重复性操作,没有什么技术含量,另外很可能忘记写映射。我只想写错误码,对应的描述信息直接用注释里的就行,所以这里介绍一下对应的工具。

go generate
go有很多工具,大家可以通过go命令查看。

![image-20210321123427848](/Users/bytedance/Library/Application Support/typora-user-images/image-20210321123427848.png)

go generate是 Go 自带的工具
展开
评论