GOLANG "Named" transfers?

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 "enumeration" that wants to "reuse" the name, I get an error:

 type hotelVisit int const ( registered hotelVisit = iota checked-in checked-out ) 

Here, if I try this, I cannot distinguish between the topic Status.registered and hotelVisit.registered, since "registered" was previously registered - is there a way to "namespace" the names "enum"?

+10
source share
3 answers

Create a new package for each of the enumerations you want to define. This means creating a subdirectory with the go file, which has a "package topicStatus" with an internal definition of const (the name of the subdirectory is the same as the package name). Remember that all defined constants must be uppercase in order for them to be exported. Do the same for "hotelVisit" and all you need. Your program will import these packages and then use them as needed: hotelVisit.Registered, topicStatus.Registered.

+9
source

Pollution of the namespace with multiple lowercase identifiers with a common word that can cause naming conflicts is not something that I consider Go idiomatic. The same goes for creating packages for storing multiple persistent ads only.

I would 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.

+9
source

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

  type TopicStatusType int const ( registered topicStatus = iota active ... ) var TopicStatus = struct{ Registered TopicStatusType Active TopicStatusType ... }{ Registered: registered, Active: active, ... } 
0
source

All Articles