GOLANG “Namespaced” enums?

2020-08-14 07:45发布

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?

标签: go
3条回答
女痞
2楼-- · 2020-08-14 08:07

One workaround is to use an anonymous struct to define a namespace.

    type TopicStatusType int
    const (
       registered topicStatus = iota
       active
       ...
    )
    var TopicStatus = struct{
        Registered TopicStatusType
        Active TopicStatusType
        ...
    }{
        Registered: registered,
        Active: active,
        ...
    }
查看更多
Juvenile、少年°
3楼-- · 2020-08-14 08:14

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.

查看更多
一纸荒年 Trace。
4楼-- · 2020-08-14 08:14

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.

查看更多
登录 后发表回答