96 points · by gopherguides · 5y ago · 106 comments
So far I still haven't found a clean way to have proper enums, and this article shows us that unfortunately neither the author has :(
I love Go for many decisions that have been made during its development, but the handling of enumerations is certainly not part of it.
It's not great for a number of reasons. First of all, `nil` is always a valid permutation even if we don't want it to be. Secondly, it's a lot of work to express the constraints we want. Thirdly, it's not perfectly type-safe; someone who was determined to shoot themselves in the foot could construct other instances of our "singleton types" if they really wanted to. Fourthly, boxing all of these values will almost certainly cause unnecessary allocations which would be a bummer if we wanted to create a lot of these quickly (this is an implementation detail and may not be any worse than a language with first-class support for sum types).
X interface{} // int(3) | int(5) | []float64 | *Z
It sucks. data Genre = Adventure
| Comic
| Crime
| ...
deriving (Show)The same is true for a `Genre(0)`, which is easy to make by accident with just a `var genre Genre` declaration (that's a `Genre(0)` already). Or by ignoring an error return, like in `json.Unmarshal(data, &genre)` (that func returns an error, but that fact is invisible in text, and you are not required to assign or handle it. fun for code reviews!).
You can also have a Genre-arg func like `func GenreToString(g Genre) string` and call it with `GenreToString(12345)` and that'll also compile.
---
Go does not have anything even remotely like enums. It has a short-hand for auto-incrementing constants, nothing more. As if that were somehow the most valuable part of constants / enums.
On the one hand: Good language support for a specialized type and a method on that type, without making the type a heavyweight class (i.e. all that magic can happen at compile-time; Genre can still be an int "under the hood").
On the other hand: wow, that's a lot of boilerplate to write just to get the string representation of a token the compiler already knows about. As other commenters have noted, `go generate` will decrease the amount of code that needs to be hand-written, but it still smells like something the language should handle without explicit code.
Although we did survive with them and delivered code into production, it doesn't mean we keep using them 20-30 years later.
I really do enjoy Go, but there are several examples of things like enums that are left out because there is some way of doing it otherwise to only the theoretical advantage of “elegance” at the cost of developer productivity.
It also doesn't touch on the other useful "system" funcs to include on a type (Scan, Value, Marshal, etc)
I didn't go into any of the Scan/Value/Marshal etc as it was a little beyond the scope of this article. I can certainly do a follow up article on it though
Thanks for the feedback!
* yes I know time.IsZero() is a thing, and the semantics are similar, but I want the compiler to warn me if I'm trying to use a time without checking if it's actually initialised first.
It needs sum types and pattern matching. Once you have used them, not having them is a huge gray void. Const expr, interfaces, sum types and pattern matching get you 85% of the way there.
I think it'd make more sense to just make a idiomatic struct:
type Genre struct {
id int
name string
}
func New(id int, name string) Genre {
return Genre {id, name}
}
Then, you can define your categories normally: var (
Adventure = genre.New(1, "Adventure")
Comic = genre.New(2, "Comic")
// etc
)
And have a O(1) String() method that doesn't need to be edited every time a new category gets added/removed/changed: func (g Genre) String() string {
return g.name
}
You can also change the implementation of the type without breaking consumers (e.g. maybe you want a pointer to a struct instead of a struct)This also means that you don't accidentally leak an "is-a" relationship between the nominal type and the underlying implementation type
var foo Genre = Adventure
foo + 1 // ought to throw a compilation error!> var (
> Adventure = genre.New(1, "Adventure")
> Comic = genre.New(2, "Comic")
> // etc
> )
Yet there is nothing preventing anyone from reassigning Adventure to genre.New(2, "Comic") or some other arbitrary value. The fact that golang doesn't have the equivalent of Java's `final` is just poor design.
Secondly, `final` serves as strong and clear documentation. We know just from looking at the definition that this is variable is not going to be re-bound.
On a side note, this compiles in golang:
func main() {
true := false
if !true {
fmt.Println("wat")
}
}That Java dropped C++-style `const` is also poor design.
We're just all really bad at this.
I think that Rust's approach is superior to C++'s here, but even that has some issues so they have to retort to interior mutability via RefCell.
Personally I use stringer[1] to handle all the string generation and then implement the valuer and scanner interfaces on that type. Boom transparent mapping between useful values and their corresponding db representation without having to write so much boilerplate.
type Book = {
id: number;
name: string;
genre: Genre;
};
type Genre =
| "Adventure"
| "Comic"
| "Crime"
| "Fiction"
| "Fantasy"
| "Historical"
| "Horror"
| "Magic"
| "Mystery"
| "Philosophical"
| "Political"
| "Romance"
| "Science"
| "Superhero"
| "Thriller"
| "Western";Mind. Blown.
My biggest typescript gripe is the fact that interface and type are _nearly_ interchangable, and many codebases just use interface wholemeal where it isn't really appropriate.
The type and interface is just because they are structural typing. It's attempting to stay faithful to JavaScript after all. Without that then the intuition breaks and not consistent.
const someBook: Book = {
id: 1,
name: "Title",
genre: "wstern"
// Compile error: [tsserver 2322] [E] Type '"westrn"' is not assignable to type 'Genre'.
};
That's not how string literals work in Typescript. If you mis-type the string you'll get a compile error. It won't make it to runtime.Some people love reinventing the past.
"go generate" is really a red herring. It's completely meaningless. It allows you to define some commands that get run when you type "go generate", but... if I define a shell script called "blah", I can get some commands to run every time I type "blah". go generate doesn't do anything useful.
In Go i actually revert to the old C custom of adding a private length value at the end so i can iterate over all values.
Like so
type Color int
const (
Blue Color = iota
Green
Red
limit
)
for i := Blue; i < limit; i++ { ... }
Go really needs proper enums...I searched recently and most of what I saw were either in depth books about the language itself, outdated blog posts, or non-relevant books that just happened to use go to explore an unrelated topic.
To the parent post, there are several articles on Go Beyond[1] that walk through development of an open-source, real-world application called WTF Dial[2]. The source is available on GitHub and you can ask Go application design questions on the Discussions board[3].
I don't understand why you would ever want to possibly save space in a database at the cost of consuming it in your binaries instead. You're almost certain to deploy more copies of your binaries than you are of your database.
Plenty of problem spaces still wish to repeat the same value many times and give it a more human readable name when necessary and not coordinate a shared DB connection or even a dynamic string pool.
On the other hand, the efficiency concern it presents is real, and just repeating "sum types" is not, alone, enough to address it. Many languages with sum types would still store, and even more still serialize, a string.
If you are serializing this data a lot, then having ints vs strings is a significant advantage.
Again, it depends on your use case. If you don't care about serialization size, then I agree, it's extra effort that you may not need.
Even in this era of fast computers and preposterously large storage, one sometimes hits a situation where the way to get the improvements you need is to start number-representing your strings.
And yes, you may not start with ints, but you could easily add code for the marshal/unmarshal later on to convert those strings to ints for serialization purposes. And it wouldn't require a change to any of your other code, not to mention that if you stored these values in a database already you don't need to perform a migration either.
A {
Field1: field1,
Field2, field2,
}
Now adding a new field to A would require ensuring that all code paths initialize Field3, otherwise you're going to have silent errors at runtime. This has been solved ages ago in Java and C# and similar languages by means of constructors.Code generation is always the last resort.
Where I work we are a go house, and the number of tools I've seen in our pre-commit configurations and in our development environment setup scripts is pretty intense. So is the number of questions around said tooling. There's a lot more friction than I'd expect. I can't even use lack of experience as an excuse for these questions because they're really talented people. Some of them have worked on the product for years, and have literally moulded the product's tooling into what it is today.
// pill.go
package painkiller
//go:generate stringer -type=Pill
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
Then running `go generate` will yield: $ cat pill_string.go
// Code generated by "stringer -type=Pill"; DO NOT EDIT.
package painkiller
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Placebo-0]
_ = x[Aspirin-1]
_ = x[Ibuprofen-2]
_ = x[Paracetamol-3]
}
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
if i < 0 || i >= Pill(len(_Pill_index)-1) {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
Note: indentation is messing up because of Hacker News, so ignore the indentation.Book
Genre
BookToGenre
GenreToGenre
might be slower but it would have been more succinct to write and easier to read.