Case expressions

May 13, 2024

I’m back live streaming again! Join me in just over an hour! Bring your questions, too!


Expression switches

If a case expression is untyped, it is first implicitly converted to the type of the switch expression. For each (possibly converted) case expression x and the value t of the switch expression, x == t must be a valid comparison.

In other words, the switch expression is treated as if it were used to declare and initialize a temporary variable t without explicit type; it is that value of t against which each case expression x is tested for equality.

It seems to me this should all be pretty intuitive, so I don’t have a whole lot to say.

However, there is a related pattern I see a lot, which could use some attention:

func handleStatus(status myStatus) {
	switch status {
		case myStatus("foo"):
			/* handle foo */
		case myStatus("bar"):
			/* handle bar */
		case myStatus("baz"):
			/* handle baz */
	}
}

In many cases, the explicit conversion to myStatus type can be omitted. But at the very least, the code can be made less verbose (and potentially more efficientY0 by doing a conversion in only one place:

func handleStatus(status myStatus) {
	switch string(status) {
		case "foo":
			/* handle foo */
		case "bar":
			/* handle bar */
		case "baz":
			/* handle baz */
	}
}

See the subtle difference? Rather than converting each string to myStatus type, we convert the single myStatus type to string. One conversion, versus potentially three in this trivial example.

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe