当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang struct 实现 interface的方法

golang struct 实现 interface的方法

2018年08月06日  | 移动技术网IT编程  | 我要评论

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网