← Back to context

Comment by mdaniel

1 day ago

I get bitten by the "nil interface" problem if I'm not paying a lot of attention since golang makes a distinction between the "enclosing type" and the "receiver type"

  package main

  import "fmt"

  type Foo struct{
   Name string
  }

  func (f *Foo) Kaboom() {
   fmt.Printf("hello from Kaboom, f=%s\n", f.Name)
  }

  func NewKaboom() interface{ Kaboom() } {
   var p *Foo = nil
   return p
  }

  func main() {
   obj := NewKaboom()

   fmt.Printf("obj == nil? %v\n", obj == nil)
   // The next line will panic (because method receives nil *Foo)
   obj.Kaboom()
  }



  go run fred.go
  obj == nil? false
  panic: runtime error: invalid memory address or nil pointer dereference