0

Why can't I type-assert a nil to a pointer type? What is the logic behind this?

package main

func main() {
    var s interface{} = nil
    var p *string = nil
    var q *string = s.(*string)
    _ = q
    _ = p
}
ealfonso
  • 6,622
  • 5
  • 39
  • 67

1 Answers1

3

You can't type assert something with no type.

The static type (or just type) of a variable is the type given in its declaration, the type provided in the new call or composite literal, or the type of an element of a structured variable. Variables of interface type also have a distinct dynamic type, which is the concrete type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type). The dynamic type may vary during execution but values stored in interface variables are always assignable to the static type of the variable.

Straight from the spec (emphasis mine)

Interfaces know the type of the underlying value. For instance if I have a interface with a type MyType it can't be type asserted to *string either. You could perhaps convert its type with some work, but type assertion and type conversion are different.

Also take a look here

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T)

user3591723
  • 1,224
  • 1
  • 10
  • 22