如玉的白玫瑰冰雪纯洁,闪烁着月光般寒冷的色彩玫瑰乱舞,勾勒出你的身形,你的容貌。想看日出,想看日落,想看世间每一处角落。
golang中,一般strcut包含 interface类型后,struct类型都需要实现 interface导出的接口,从而成为相应的 interface接口类。
实际上,struct包含interface之后,并不需要实现interface的接口,也能成为 interface接口类。
代码如下:
type newEr interface {
New()
}
type testInterface interface {
newEr
Done() <-chan struct{}
}
type kkTest struct {
testInterface
}
func NewTest() newEr {
return kkTest{}
}
func main() {
kk := NewTest()
i,ok := kk.(testInterface)
fmt.Println(i,ok)
ch := i.Done()
fmt.Println(ch)
}
其中 i,ok := kk.(testInterface) 测试成功,也就是说 kkTest 已经是 testInterface 接口类,但是后续 ch := i.Done() 引发 panic,这个也是预料之内的。
相关的应用可以看 context包中的实现,valueCtx部分实现了 Context 接口函数,对其不需要的函数没有实现,如果调用了这些未实现的函数就会导致 panic。这样在程序排错其实是很有好处的,因为调用到这些接口,说明代码其实已经写错了。
到此这篇关于golang struct 如何实现 interface的方法就介绍到这了。人性最可怜的就是:我们总是梦想着天边的一座奇妙的玫瑰园,而不去欣赏今天就开在我们窗口的玫瑰.更多相关golang struct 如何实现 interface的方法内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!