Check All Enums Exist in a Switch in Go

Elliot Chance
The Startup
Published in
1 min readMay 3, 2020
Photo by Javier Allegue Barros on Unsplash

Go does not have any concept of enums like some other languages. There are arguments for and against this approach which I won’t go into here. However, there are times when you want to check that switch statements contain all enum values. Especially if you intend to add new enum values in the future and want to catch existing code that now needs to be updated accordingly.

For this, I developed a tool called switch-check. It’s a zero dependency, zero configuration CLI tool for doing just that. You can try it right now with:

go get -u github.com/elliotchance/switch-check
switch-check

Or, here is a quick example:

Will output the error:

foo.go:17:2 switch is missing cases for: FooB, FooE

Known Limitations

Using expressions to produce enum values are not supported. This level of type inference requires the compiler (not just the AST). For example this will not be recognized as a enum value:

var EnumValueA = someFuncThatReturnsAnEnumValue()

Also, switch statements must only switch on the value and not contain expressions in case statements.

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Elliot Chance
Elliot Chance

Written by Elliot Chance

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

Responses (1)