Check All Enums Exist in a Switch in Go
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.