Nil and interfaces in Go

Nil and interfaces in Go

Sergey Abbakumov

It's quite unusual to see in Go that the null interfaces are not completely null:

package main

import "fmt"

type Interface interface {
  Foo()
}

type Type struct {
}

func (t *Type) Foo() {
  if t == nil {
    fmt.Println("<nil>")
  }
}

func main() {
  var t *Type
  var i Interface = t
  if i != nil {
    i.Foo()
  }
}


Here <nil> is displayed, although we assign a null pointer to the interface type. For those who are used to the C++/C#/Java it looks interesting.


Telegram channel: https://t.me/sea_plus_plus

Report Page