Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GOLANG "Namespaced" enums?

Tags:

go

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?

like image 893
user2644113 Avatar asked May 04 '14 17:05

user2644113


2 Answers

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.

like image 112
LemurFromTheId Avatar answered Sep 23 '22 00:09

LemurFromTheId


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.

like image 21
gigatropolis Avatar answered Sep 26 '22 00:09

gigatropolis