您现在的位置是:网站首页> 编程资料编程资料
golang struct 实现 interface的方法_Golang_
2023-05-26
476人已围观
简介 golang struct 实现 interface的方法_Golang_
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中切片的用法与本质详解_Golang_
- golang中sync.Map并发创建、读取问题实战记录_Golang_
- Go语言中的上下文取消操作详解_Golang_
- golang grpc 负载均衡的方法_Golang_
- Go语言包管理工具dep的安装与使用_Golang_
- Golang对MongoDB数据库的操作简单封装教程_Golang_
- golang实战之truncate日志文件详解_Golang_
- 基于golang channel实现的轻量级异步任务分发器示例代码_Golang_
- Go语法糖之‘...’ 的使用实例详解_Golang_
- 在Go中构建并发TCP服务器_Golang_
