Type switches
…
Instead of a type, a case may use the predeclared identifier
nil; that case is selected when the expression in the TypeSwitchGuard is anilinterface value. There may be at most onenilcase.
Straight forward, right? Here’s an example:
switch x.(type) {
case int:
case string:
case nil:
}
But now here’s a question: If we assign x.(type) to a temporary variable the TypeSwitchGuard, what is its type in the nil case?
We can find out with a simple test:
var x any
var y error
switch t := x.(type) {
case nil:
y = t
}
This code fails to compile with a telling error message:
use t (variable of type any) as error value in assignment: any does not implement error (missing method Error)
So there’s our answer: In the nil case (and as we saw yesterday, the default and any other case with multiple types), the temporary variable’s type is the same as x’s type.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)