akavel's digital garden

Go pattern: tuple switch

An idiom I discovered a few years ago; I think about it as “poor man’s pattern matching” in Go:

func f(foo, bar, baz bool) {
	type tuple struct{ foo, bar, baz bool }
	switch (tuple{foo, bar, baz}) {
	case tuple{true, true, true}:
		// ...
	case tuple{true, true, false}:
		// ...
	case tuple{true, false, true},
		tuple{true, false, false},
		tuple{false, true, true}:
		// ...
	}
}

This works also for some types other than bool, notably including string, and they can be mixed in the tuple type when needed.

🌳 ripe — contents of this article got classified among complete works that I have edited and published as a cohesive whole. They are similar to a traditional blog post published at a point in time in that way—though I still tend these over time.
© Mateusz Czapliński 🐘 Mastodon 🐙 GitHub 🎮 Itch.io ♟️ BGG 🧶 Ravelry