惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
IT之家
IT之家
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
C
Check Point Blog
T
Tailwind CSS Blog
博客园 - Franky
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
J
Java Code Geeks
腾讯CDC
罗磊的独立博客
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
B
Blog
V
Visual Studio Blog
F
Fortinet All Blogs

Dizzy zone

Pangolin Private Resources With Domain Https About Redis is fast - I'll cache in Postgres n8n and large files Malicious Node install script on Google search Wrapping Go errors with caller info BLAKE2b performance on Apple Silicon State of my Homelab 2025 My homelabs power consumption On Umami ML for related posts on Hugo Probabilistic Early Expiration in Go SQLC & dynamic queries Enums in Go Streaming Netdata metrics from TrueNAS SCALE SQL string constant gotcha Moving from Jenkins to Drone My new server: MSI Cubi 3 Silent My thoughts on Ansible® Profiling gin with pprof How I host this blog, CI and tooling OAuth with Gin and Goth I made my own commenting server. Here's why. Why I hate OpenApi(swagger) IDE for GO Jenkins on raspberry pi 3 How I started my professional career Kestrel vs Gin vs Iris vs Express vs Fasthttp on EC2 nano Go's defer statement Self-hosted disqus alternative for 5$ a month
Refactoring Go switch statements
Vik · 2018-07-28 · via Dizzy zone

When writing Go code, I often end up with lots of enums that I use to fork my logic in a switch statement. Take this enum:

type MyEnum int

const (
	One   MyEnum = iota
	Two   MyEnum = iota
	Three MyEnum = iota
	Four  MyEnum = iota
	Five  MyEnum = iota
)

}

I’ll then end up with a switch in a part of my code, like so

switch myEnum {
	case One:
		err := DoSomeOtherStuff()
		if err != nil {
			return err
		}
	case Two:
		err := DoSomeMagicalStuff()
		if err != nil {
			return err
		}
	case Three:
		err := DoSomeExoticStuff()
		if err != nil {
			return err
		}
	case Four:
		err := DoSomeOtherStuff()
		if err != nil {
			return err
		}
	case Five:
		err := DoSomeStuff()
		if err != nil {
			return err
		}
}

}

When the enums are small, with only a few entries in them, this is all rather nice and readable. But take an enum that’s 10, 20, 100 entries long and a switch becomes way too long. The approach I prefer to take in these cases is construct a map containing all the required functions associated with the enum value as the key for the map.

var myMap = map[MyEnum]func() error{
	One:   DoSomeOtherStuff,
	Two:   DoSomeMagicalStuff,
	Three: DoSomeExoticStuff,
	Four:  DoSomeOtherStuff,
	Five:  DoSomeStuff,
}

}

The switch then can be gotten rid of. Instead, it becomes a map lookup:

if myFunc, ok := myMap[myEnum]; ok {
	err := myFunc()
	if err != nil {
		return err
	}
} else {
    // the default case would go here
}

}

This allows for more concise code and easier extension in the future. However, I do not use this everywhere either. If the enum is small and not going to change often(famous last words) I’ll leave the switch in its place. It does not work in places where you have functions with very different signatures for each of the switch cases either.

EDIT: Handling all the errors

As Jonathan Gold states in the comments below, you can also handle all the errors at once, so the initial switch becomes something along the lines of:

var err error
switch myEnum {
	case One:
		err = DoSomeOtherStuff()
	case Two:
		err = DoSomeMagicalStuff()
	case Three:
		err = DoSomeExoticStuff()
	case Four:
		err = DoSomeOtherStuff()
	case Five:
		err = DoSomeStuff()
}
if err != nil {
	return err
}

}

Thanks, Jonathan.

How do you approach your switches? What other tricks do you use? Let me know in the comments below.