GoLang学习笔记(三十四)接口及空接口
面向对象语言中,接口用于定义对象的行为。接口只指定对象应该做什么,实现这种行为的方法是由对象来决定的。
在Go语言中,接口是一组方法签名。
接口只指定了类型应该具备有的方法,类型决定了如何实现这些方法。
当某个类型为了接口中的所有方法提供了具体的实现细节时,这个类型就被称为实现了该接口。
接口定义了一组方法,如果某个对象实现了该接口的所有方法,则此对象就实现了该接口。
Go语言的类型都是隐式实现接口的。任何定义了接口中所有方法的类型都被称为隐式地实现了该接口。
1、定义接口:
type 接口名称 interface{
方法1([参数列表]) [返回值]
方法2([参数列表]) [返回值]
...
方法n([参数列表]) [返回值]
}
2、定义结构体:
type 结构体名 struct{
//属性
}
3、实现接口方法:
func (变量名 结构体类型) 方法1([参数列表]) [返回值]{
//方法体
}
func (变量名 结构体类型) 方法2([参数列表]) [返回值]{
//方法体
}
...
func (变量名 结构体类型) 方法n([参数列表]) [返回值]{
//方法体
}
type phone interface {
call()
}
type andriod struct {
}
type iphone struct {
}
func (a andriod) call() {
fmt.Printf("我是安卓手机,开始打电话! \n")
}
func (i iphone) call() {
fmt.Printf("我是苹果手机,开始打电话! \n")
}
func testInterface01() {
var p1 phone
p1 = new(andriod)
fmt.Printf("变量p1的类型:%T,值:%v,指针:%p \n", p1, p1, p1)
p1.call()
p1 = new(iphone)
fmt.Printf("变量p1的类型:%T,值:%v,指针:%p \n", p1, p1, p1)
p1.call()
}
运行testInterface01()函数,你会发现变量类型是指针。
func testInterface02() {
var p1 phone
p1 = andriod{}
fmt.Printf("变量p1的类型:%T,值:%v,指针:%p \n", p1, p1, &p1)
p1.call()
p1 = iphone{}
fmt.Printf("变量p1的类型:%T,值:%v,指针:%p \n", p1, p1, &p1)
p1.call()
}
运行testInterface02()函数,你会发发现变量类型不再是指针。
得出使用new()函数生成的结构体是结构体的指针类型。
空接口
空接口:该接口红没有任何的方法。任意类型都可以实现该接口
空接口的定义:interface{} 也就是包含0个方法的接口
空接口表示任意数据类型,类似于java中的object
空接口例子:
type a interface {
}
type cat struct {
name string
age int
}
type person struct {
name string
sex bool
}
func showEntity(a a) {
fmt.Printf("变量类型:%T,变量的值%v \n", a, a)
}
func testNilInterface1() {
var nif1 a = cat{"miaomiao", 3}
var nif2 a = person{"ketty", true}
var nif3 a = "hello hello hello"
var nif4 a = 1234567
var nif5 a = 3.14157
showEntity(nif1)
showEntity(nif2)
showEntity(nif3)
showEntity(nif4)
showEntity(nif5)
}
空接口的常用情况:
func testNilInterface2() {
//1、println的参数就是空接口
fmt.Println("hehehehehe", 1234567, 3.14157, cat{"mimi", 2}, person{"ketty", false})
//2、定义一个map:key是string,value是任意数据类型
map1 := make(map[string]interface{})
map1["name"] = "dani"
map1["age"] = 33
map1["sex"] = true
fmt.Println(map1)
//3、定义一个切片,其中存储任意类型的数据
slice1 := make([]interface{},0,10)
slice1 = append(slice1,1234567,"heiheihei",3.14157,cat{"xueqiu",2},person{"danni",true})
fmt.Println(slice1)
}
到此这篇关于“GoLang学习笔记(三十四)接口及空接口”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!
您可能感兴趣的文章:
GoLang学习笔记(三十四)接口及空接口
go语言学习笔记(十三)——接口类型
go struct 成员变量后面再加个字符串是什么意思?_Go语言的学习笔记(第十章) 接口...
想系统学习GO语言(Golang
利用PS制作“签名”GIF小动画的例子
golang基础教程
Golang学习笔记(五):Go语言与C语言的区别
GoLang学习笔记(三十六)接口对象的转型
Golang学习笔记(十二):接口的声明与使用
Go学习--interface(接口)