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。這樣在程序排錯其實是很有好處的,因為調用到這些接口,說明代碼其實已經寫錯了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 使用go的interface案例實現多態范式操作
- Go語言實現類似c++中的多態功能實例
- golang語言如何將interface轉為int, string,slice,struct等類型
- golang基礎之Interface接口的使用
- golang中struct和interface的基礎使用教程
- Go之interface的具體使用
- Go語言中你不知道的Interface詳解
- golang中interface接口的深度解析
- 淺談Go語言多態的實現與interface使用