Hi, I have this example:

package main

import (
       "fmt"
       "time"
)

func main() {
       fmt.Println("Simple test")
       test(nil)

       fmt.Println()

       fmt.Println("Base test")
       var b *base
       b = nil
       test(b)

       fmt.Println()

       time.Sleep(1 * time.Second)
       fmt.Println("Sub test")
       var s *sub
       s = nil
       test(s)
}

type inter interface {
       Test()
}

type base struct {

}

func (i *base) Test() {
       fmt.Printf("IMPL INVOKED ON NIL %s", i)
}

type sub struct {
       base
}

func test(intr inter) {
       if intr != nil {
              fmt.Printf("Is not nil %v\n", intr)
              intr.Test()
       } else {
              fmt.Printf("Is nil %v NOT INVOKED ON NIL \n", intr)
       }
}


And get the following result:

Simple test
Is nil <nil> NOT INVOKED ON NIL 

Base test
Is not nil <nil>
IMPL INVOKED ON NIL %!s(*main.base=<nil>)

Sub test
Is not nil <nil>
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4014e5]

goroutine 1 [running]:
panic(0x4920c0, 0xc42000a0b0)
/usr/lib/go-1.7/src/runtime/panic.go:500 +0x1a1
main.(*sub).Test(0x0)
<autogenerated>:2 +0x5
main.test(0x4f9180, 0x0)

Could anyone explain why it happens? Why nil checking is working for the 
first case and doesn't  work for rest of cases?
Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to