Reputation: 124
I want to check for nil
in a type switch. What type do I use for nil
in a switch case?
switch v := v.(type) {
case int:
fmt.Println("it's an integer", v)
case ????: <--- what type do I put here?
fmt.Println("it's nil!")
}
Upvotes: 0
Views: 2712
Reputation:
Use nil
to check for a nil interface value in a type switch:
switch v := v.(type) {
case int:
fmt.Println("it's an integer", v)
case nil:
fmt.Println("it's nil!")
}
A nil interface value does not have a dynamic type. In the context of a type switch case, nil
represents "no dynamic type".
Upvotes: 2
Reputation: 3524
You should check whether v
is nil outside of your type switch.
if v == nil {
// Do stuff probably return or error out?
}
switch v := v.(type) {
// ...
}
Upvotes: 0
Reputation: 369574
I want to check for
nil
in a type switch. What is the type ofnil
?
There is not a single place in the Go Language Specification that specifies nil
, but there are multiple places that make it clear that nil
has no type [bold emphasis mine]:
In the section on Variables:
unless the value is the predeclared identifier
nil
, which has no type
In the sub-section on Expression switches:
The predeclared untyped value
nil
[…]
Even if the Go Language Specification did not explicitly say that nil
has no type, it should at least be obvious that nil
cannot possibly have a single type. At least not a type that is expressible within Go.
nil
is a valid value for
This means that the type of nil
must be all of those types at the same time. There are a couple of ways in which this could be achieved: The type of nil
could be
However, Go doesn't have union types, it doesn't have intersection types, it doesn't have subtyping, and it doesn't have polymorphic types, so even if nil
had a type, this type would not be expressible in Go.
Alternatively, the designers of Go could declare that nil
doesn't have one type, it has multiple types, but that wouldn't help you either: you would have to have cases for all the possible types nil
can have, but those cases wouldn't apply only to nil
. You would need to have a case for pointers, but that case would apply to any pointer not just to a nil
pointer, and so on.
It is possible to check for a nil
interface type, however. See the sub-section on 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 anil
interface value. There may be at most onenil
case.
Upvotes: 8