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变量的数据类型

Go singleton

毛剑:bilibili 的 Go 服务实践(上篇)

关于Go get超时的问题

安装Go第三方库的方法

Golang如何打印单引号和双引号

Go操作mysql

Go1.4 bootstrap 源码安装新版Go

Golang web需要框架么

Golang 创建型设计模式 工厂方法

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




打赏

取消

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

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

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

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

评论

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