您现在的位置是:网站首页> 编程资料编程资料

golang struct 实现 interface的方法_Golang_

2023-05-26 474人已围观

简介 golang struct 实现 interface的方法_Golang_

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。这样在程序排错其实是很有好处的,因为调用到这些接口,说明代码其实已经写错了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

-六神源码网