华域联盟 Golang golang struct 实现 interface的方法

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

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

本文由 华域联盟 原创撰写:华域联盟 » golang struct 实现 interface的方法

转载请保留出处和原文链接:https://www.cnhackhy.com/111632.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Go语言基础map用法及示例详解

下一篇

已经没有了

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们