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怎么搭一个网站

Golang中mysql建立连接超时时间timeout

[系列] - Go-gin-api 路由中间件 - 日志记录(三)

Go get下载包失败问题

简介

Go的值类型和引用类型1——传递和拷贝

Golang能写人工智能吗

Golang编译为什么快

Go - struct{} 实现 interface{}

Golang中的切片与gc

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




打赏

取消

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

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

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

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

评论

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