Although go cannot create constant of type map, but it can be achieved in multiple ways.
type ErrorCode string
const (
E270_01 ErrorCode = "270.01"
E270_02 = "270.02"
)
var ErrDescription = map[ErrorCode]string{
E270_01: "this is error description",
E270_02: "this is error description",
}
type LogErr struct {
Code ErrorCode
Description string
}
func getLogErr(e ErrorCode) LogErr {
return LogErr{
Code: e,
Description: ErrDescription[e],
}
}
func TestErrorConstant(t *testing.T) {
fmt.Println(getLogErr(E270_01))
}
This solves our purpose. But the problem is for every new error, we need to change things at two places, (1) Declare const like E270_02 (2) Add an entry in the ErrDescription map
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Another possible way looks like :-
type ErrorCode string
const (
E270_01 ErrorCode = "270.01:this is error description"
E270_02 = "270.02:this is error description"
)
type LogErr struct {
Code string
Description string
}
func getLogErr(e ErrorCode) LogErr {
token := strings.Split(string(e), ":")
return LogErr{
Code: token[0],
Description: token[1],
}
}
func TestErrorConstant(t *testing.T) {
fmt.Println(getLogErr(E270_01))
}
This way looks promising, but don't really like the way of splitting string using ":"
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I think best way could have been something like ---
const (
E270_01 ErrorCode = {"270.01", "this is error description"}
)
Since Golang doesn't support the Constant of struct, what could be your approach?
Any suggestion is really appreciated.