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

相关阅读 >>

Golang 一份漂亮的dockerfile

手撸Golang Go与微服务 saga模式之3

Golang viper 使用记录: 读取不到配置文件json

Golang使用for循环的一个小技巧

Gox语言中的全局变量与局部变量-gx52

Go build和Go install的区别

Golang 架构设计原则 单一职责原则

手撸Golang Go与微服务 聚合模式

Golang格式化符号%b是什么意思

Golang 在 runtime 中的一些骚东西

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




打赏

取消

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

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

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

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

评论

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