golang struct 實現(xiàn) interface的方法
golang中,一般strcut包含 interface類型后,struct類型都需要實現(xiàn) interface導(dǎo)出的接口,從而成為相應(yīng)的 interface接口類。
實際上,struct包含interface之后,并不需要實現(xiàn)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 已經(jīng)是 testInterface 接口類,但是后續(xù) ch := i.Done() 引發(fā) panic,這個也是預(yù)料之內(nèi)的。
相關(guān)的應(yīng)用可以看 context包中的實現(xiàn),valueCtx部分實現(xiàn)了 Context 接口函數(shù),對其不需要的函數(shù)沒有實現(xiàn),如果調(diào)用了這些未實現(xiàn)的函數(shù)就會導(dǎo)致 panic。這樣在程序排錯其實是很有好處的,因為調(diào)用到這些接口,說明代碼其實已經(jīng)寫錯了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Go中的格式化字符串fmt.Sprintf()和fmt.Printf()使用示例
這篇文章主要為大家介紹了Go中的格式化字符串fmt.Sprintf()和fmt.Printf()使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06
我放棄Python轉(zhuǎn)Go語言的9大理由(附優(yōu)秀書籍推薦)
這篇文章主要給大家介紹了關(guān)于我放棄Python轉(zhuǎn)Go語言的9大理由,以及給大家推薦了6本優(yōu)秀的go語言書籍,對同樣想學(xué)習(xí)golang的朋友們具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10

