Go 錯誤碼初始化
錯誤碼是程式中,經常需要用到的,一般在
Map中定義…
key為code,value為msg
1.Map初始化
由于這個Map只需要初始化一次,所以,可以使用Go基礎包中的sync.Once,
來保證,Init只運行一次,極大的減少了程式的運行開銷,
2.代碼
此處以單元測驗的形式體現,
Go語言的單元測驗,可以看我的另一篇博文,
import (
"fmt"
"sync"
"testing"
)
var once sync.Once
var mapErrMsg map[int32]string
func TestOnceDo(t *testing.T) {
fmt.Println(GetErrorMsgForCode(0))
fmt.Println(GetErrorMsgForCode(1))
fmt.Println(GetErrorMsgForCode(2))
fmt.Println(GetErrorMsgForCode(3))
}
func GetErrorMsgForCode(code int32) string {
// 雙重保障
if len(mapErrMsg) == 0 {
InitErrorMap()
}
strMsg, ok := mapErrMsg[code]
if !ok {
strMsg = "未知錯誤"
}
return strMsg
}
// 初始化ErrorMap
func InitErrorMap() {
once.Do(func() {
mapErrMsg = make(map[int32]string)
mapErrMsg[0] = "成功"
mapErrMsg[1] = "熔斷了"
mapErrMsg[2] = "淦"
fmt.Println("運行了")
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/233543.html
標籤:區塊鏈
上一篇:BitOffer交易所好不好?
