In NodeJS, when we want to declare some constant variable and would like them to be used across the project, we might write something like:
// const.js
module.exports.mqttQOS = {
AtMostOnce: 0,
AtLeastOnce: 1,
ExactlyOnce: 2,
};
Therefore, we could use it like constant.mqttQOS.AtMostOnce
, and throw an error when we use constantQOS.ErrorRefering
.
In Golang we could only do something like:
var mqttQoS = map[string]byte{
"AtMostOnce": 0,
"AtLeastOnce": 1,
"ExactlyOnce": 2,
}
And use it as: fmt.Println(mqttQoS["AtMostOnce"]) // print: 0
However, it'll print fmt.Println(mqttQoS["ErrorRefering"]) // print: 0
because of the characteristic of Golang map (like Python's defaultdict() )
Althought we could do something to prevent this error referring by:
var mqttQoS = map[string]byte{
"AtMostOnce": 0,
"AtLeastOnce": 1,
"ExactlyOnce": 2,
}
result, ok := mqttQoS["ErrorRefering"]
if ok {
fmt.Println("value: ", result)
}
So back to my question, other than using ok
to limit the error referring, is there any better practice to work on the nested constant objects in Golang?
Updated: so that I could use like mqttQoS.AtMostOnce
and will raise an error when I mqttQos.ErrorRefer
.
Defining another type
is one way, but is it common practice in big projects?
Thanks!
Referred to the comments, using nested const is not the common practice in Golang.
constant literal
might be the solution to the question.
There are related discussions and proposals on github.com/golang
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.