如何知道一个接口的功能没有实现?

How to known a function of a interface is not realized?

我刚刚在 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()
}

可以是go buildgo run。但是会收到像这样的恐慌:

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

我怎么知道a.aaa()没有实现

变量a的类型为inter,一个接口,指向impl。结构 impl 中嵌入了 inter 接口。这意味着 impl.aaa() 存在,这实际上意味着 impl.inter.aaa()。但是在您的代码中 impl.inter 为零。为了更清楚:

b:=impl{}
var a inter
a=b
a.aaa() // this will call b.inter.aaa(), but b.inter is nil