怎么知道接口的功能没有实现? [英] How to known a function of a interface is not realized?
本文介绍了怎么知道接口的功能没有实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚在Go中尝试了以下代码.
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()
}
可以是 go build
和 go run
.但会收到类似的恐慌:
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
我怎么知道 a.aaa()
没有实现.
推荐答案
变量 a
的类型为 inter
,该接口指向impl
.结构 impl
中嵌入了 inter
接口.这意味着 impl.aaa()
存在,实际上意味着 impl.inter.aaa()
.但是,在您的代码中, impl.inter
为零.为了更清楚一点:
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
这篇关于怎么知道接口的功能没有实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文