Closed nightway1 closed 10 months ago
There are many ways to implement enums in Go depending on the direction the language takes.
So just as you have already labelled it v2 yourself, I wouldn't hold my breath too much until some time in the future.
But you can also take advantage of the current features and implement your enums nowadays if you find iotas unfit for your use case.
You can define a struct where enum cases are methods that return a comparable type.
E.g.
type country struct{string}
type Country struct{}
func(c Country) Australia() country {...}
func(c Country) Canada() country {...}
func(c Country) China() country {...}
func(c Country) England() country {...}
func(c Country) France() country {...}
func(c Country) Germany() country {...}
func(c Country) Japan() country {...}
func(c Country) Mexico() country {...}
func(c Country) Morocco() country {...}
func(c Country) Zimbabwe() country {...}
// ...
It even has the non negligible advantage that the unexported country
type can itself have its own methods. For example, you could define one that returns the country's languages.
Some kind of enum hierarchy. It's at will and very type-safe.
Duplicate of #19814
Go Programming Experience
Intermediate
Other Languages Experience
Python
Related Idea
Has this idea, or one like it, been proposed before?
Yes.
I am making this proposal since the last proposal I found was from 2017, it is better that there is a more current one, on that topic they spoke very positively about it being in go, so you already know what to do.
Does this affect error handling?
No.
Is this about generics?
No.
Proposal
add a much better way of defining enums, like:
type BetterEnum enum { FIRST = "enumsaregood" SECOND = "oldenumsarebad" }
According to me and many, it is a much more readable way than doing things with constants and types.
Language Spec Changes
No response
Informal Change
No response
Is this change backward compatible?
Yes.
There is no way to remove the old way of doing it, because they would remove the constants and that makes no sense.
Orthogonality: How does this change interact or overlap with existing features?
No response
Would this change make Go easier or harder to learn, and why?
No response
Cost Description
No response
Changes to Go ToolChain
No response
Performance Costs
No response
Prototype
(https://github.com/golang/go/issues/19814)