Type assertion and nil

A concrete type is taken out of an interface explicitly. A nil pointer inside an interface is no longer a nil interface.

An interface stores a pair: a concrete type and a value. While both are empty, the interface equals nil.

var p *int
var i any = p
i == nil // false

p equals nil, but i already knows the type *int. The comparison i == nil is false. This is the best-known trap in the language. A function that returns the interface error must not do var err *MyError and return err when there is no error. It must return nil with no concrete type. Otherwise the caller sees a "non-nil" error that has nil inside.

A concrete type is taken out with an assertion:

s, ok := v.(string)

The form with two results does not panic: ok will be false if the type is different. The form v.(string) without ok panics. In ordinary code, take two results. A type switch sorts several types at once:

switch v.(type) {
case nil:
    return "пусто"
case int:
    return "число"
case string:
    return "строка"
default:
    return "другое"
}

int and int32 are different cases. any does not erase the concrete type. It hides it until you check.

Do not use a type assertion as an ordinary method call. If you assert the same type in ten places, you need a method on the interface, not a ladder of switch. An assertion belongs at a boundary: unpack an error, recognize io.EOF, pull out extra behavior through a small second interface.

Practice

  1. Nil inside an interface

    var p *int and var i any = p. What is i == nil equal to?

    • true, because p equals nil
    • false, because the interface contains the type *int
    • The code does not compile
    • A panic on the comparison
  2. A short description

    Write Describe(v any) string. For a nil interface return пусто, for int return число, for string return строка, and for any other concrete type return другое. int32 is already другое.

  3. A safe assertion

    How do you take a string out of any without risking a panic if a number is inside?

    • s := v.(string)
    • s, ok := v.(string)
    • s := string(v)
    • s := v.String()