-1

I just tried the following code in Go.

package main

type inter interface {
    aaa() int
}

type impl struct {
    inter
}

func main() {
    var a inter
    a = impl{}
    // how to check the function for interface `inter` is not realized?
    a.aaa()
}

It can be go build and go run. But will receive a panic like:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x8972c]

goroutine 1 [running]:
main.(*impl).aaa(0x40c018, 0x41a788, 0xb2ae0, 0x40c018)
    <autogenerated>:1 +0x2c
main.main()
    /tmp/sandbox029518300/prog.go:15 +0x60

How can I know the a.aaa() is not realized.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
lzmhhh123
  • 21
  • 4

1 Answers1

0

The variable a is of type inter, an interface, which is pointing to an impl. The struct impl has the inter interface embedded in it. That means impl.aaa() exists, which actually means impl.inter.aaa(). However in your code impl.inter is nil. To make it more clear:

b:=impl{}
var a inter
a=b
a.aaa() // this will call b.inter.aaa(), but b.inter is nil
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Thanks for your answer. So the only way to avoid the panic for the situation is to check the `Type` of `inter`? – lzmhhh123 Jan 03 '20 at 08:13
  • @lzmhhh123, no, you just have to initialize your struct correctly. Don't leave the inter field nil. – Peter Jan 03 '20 at 08:30