Go-Interface


本文摘自网络,作者,侵删。

Go 接口

Interface定义

在golang中,接口是一种抽象类型,接口可理解为一组方法的集合。
跟Struct结构一样,通过type来进行定义

type someInterface interface{
    method1(params) returnValue
    method2(params) returnValue
    …
}

ps:

  • 参数和返回值中的变量名可省略,只写参数类型即可。
  • 一个对象只要实现了接口中的所有方法,那么就实现了这个接口
  • 对于值类型的接口接收者,传入值类型变量,指针类型变量均可

接口嵌套

type someInterface1 interface{
    fmt.Println("interface1")
}

type someInterface2 interface{
    fmt.Println("interface2")
}

type someInterface interface {
    someInterface1
    someInterface2
}

接口的实现分布在多个结构体中

type someInterface interface {
    method1
    method2
}
type FatherObj struct{}

func (FatherObj) method1{
    ...
}

type SubObj struct{
    FatherObj
}

func (SubObj) method2{
    ...
}

// FatherObj 实现 method1, SubObj 通过实现 method2 即实现了 someInterface 
var target someinterface
target = SubObj{}
target.method1()
target.method2()

空接口

由于空接口没有定义任何方法,也就是说任何类型都实现了空接口,对于空接口类型的变量,可以用任意类型给其赋值

type noneInterface interface{}

应用场景:对于某个方法的参数,不关心其具体类型,都做相同的逻辑处理的时候


本文来自:简书

感谢作者:SodaCrush

查看原文:Go-Interface

相关阅读 >>

Go语言两种版本的hello world你会吗

Go 时间格式化 字符串格式化为时间格式

jack liu's Golang personal summary notes

Golang如何接收输入

如何用 Go 语言写出好用的 http 中间件?

了解Go中如何使用包、变量和函数

Golang如何升级?

Golang变量的数据类型

编写可测试的 Go 代码

Go语言入门

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...