Go 错误码初始化

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("运行了")
	})
}

猜你喜欢

转载自blog.csdn.net/LitongZero/article/details/111032051