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。這樣在程序排錯其實是很有好處的,因為調用到這些接口,說明代碼其實已經寫錯了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答