Check All Enums Exist in a Switch in Go

Elliot Chance
May 3 · 1 min read
Image for post
Image for post
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

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

Medium's largest active publication, followed by +719K people. Follow to join our community.

Elliot Chance

Written by

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

The Startup

Medium's largest active publication, followed by +719K people. Follow to join our community.

Elliot Chance

Written by

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

The Startup

Medium's largest active publication, followed by +719K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store