Two final items with regard to type switches, before we move on to the next topic:
Type switches
…
The type switch guard may be preceded by a simple statement, which executes before the guard is evaluated.
This is pretty straight forward. It works just like the simple statements in if
statements and normal switch
statements. A simple statement can be used both with or without a temporary variable. In other words, both of these are valid:
switch x := someFunc(); x.(type) {
switch x := someFunc(); t := x.(type) {
The “fallthrough” statement is not permitted in a type switch.
And finally, fallthrough
isn’t valid with a type switch. As much as you might like to do something like:
switch x.(type) {
case int8:
fallthrough
case int16:
fallthrough
case int:
/* handle integer types */
}
This isn’t possible. It would wreak all kinds of havoc if it were allowed—what is the actual type of the variable when a case int
falls through to a case error
, for example?
Of course you can group like types in a single case:
switch x.(type) {
case int, int8, int16, ...:
With the caveat previously mentioned that it won’t work with temporary variables.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)