blunder
blunder

Reputation: 124

What is the type of nil?

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

Answers (3)

user13631587
user13631587

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!")
}

Run it on the playground.

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

kingkupps
kingkupps

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

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369574

I want to check for nil in a type switch. What is the type of nil?

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]:

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

  • pointers,
  • functions,
  • interfaces,
  • slices,
  • channels, and
  • maps.

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

  • a union type of all of those types,
  • an intersection type of all of those types (but that wouldn't be type-safe), or
  • a subtype of all of those types, or
  • a polymorphic type.

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 a nil interface value. There may be at most one nil case.

Upvotes: 8

Related Questions