I understand that the idiomatic way to create an enum in GO is as follows:
type topicStatus int
const (
registered topicStatus = iota
active
inactive
pending-removal
removed
)
but if I have another "enum" that wants to "reuse" a name, I get an error:
type hotelVisit int
const (
registered hotelVisit = iota
checked-in
checked-out
)
Here, if I try this, I cannot differentiate between topicStatus.registered and hotelVisit.registered as "registered" was previously used - is there a way to "namespace" the "enum" names?
Polluting the namespace with numerous common word lower case identifiers that are likely to cause naming conflicts isn't something I'd consider idiomatic Go. Same goes for creating packages just to hold a handful of constant declarations.
I'd probably do something like this:
type topicStatus int
const (
tsRegistered topicStatus = iota
tsActive
tsInactive
tsPendingRemoval
tsRemoved
)
type hotelVisit int
const (
hvRegistered hotelVisit = iota
hvCheckedIn
hvCheckedOut
)
Now you can declare and initialize with ts := tsPendingRemoval
. Clear and concise with little risk of naming conflicts.
Create a new package for each of the enums you want to define. This means creating a sub-directory with a go file the has "package topicStatus" with the const definition inside (sub-directory name is the same as the package name). Remember all the constants defined must be upper case so they are exportable. Do the same for "hotelVisit" and whatever you need. Your program will import these packages and then use them as needed: hotelVisit.Registered, topicStatus.Registered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With