golang struct 实现 interface的方法
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中的格式化字符串fmt.Sprintf()和fmt.Printf()使用示例
这篇文章主要为大家介绍了Go中的格式化字符串fmt.Sprintf()和fmt.Printf()使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-06-06


最新评论