Go 语言接口
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
实例
/* 定义接口 */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* 定义结构体 */
type struct_name struct {
/* variables */
}
/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
/* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* 方法实现*/
}
a、定义多个结构体
b、为每个结构体定义一个相同的方法,比如我们下面的事例,Say
c、定义一个接口,这个接口的内容就是步骤b定义的Say()方法
d、在定义一个函数,这个函数,这个函数的参数类型就是步骤c定义的接口
e、调用步骤d的函数,传递一个步骤b定义的结构体进去 就实现了多态
1、go语言的多态是用接口来实现的interface
package main
import "fmt"
//面向对象的多态是通过接口interface来实现的,不同的对象,调用相同的接口,实现不同的效果
//go语言中,接口interface是一个自定义类型,描述了一系列方法的集合,关键字interface
//接口不能被实例化
//定义接口的方法
//type 接口名字 interface {
//
//}
//接口的名字一般以er结尾
//定义一个Personer的接口
type Personer interface {
Say()
}
//定义一个学生的结构体
type Studentxxx struct {
name string
score int
}
type Teacherxxx struct {
name string
class string
}
func (s *Studentxxx) Say () {
fmt.Println(s.name,s.score)
}
func (s *Teacherxxx) Say () {
fmt.Println(s.name,s.class)
}
type Mystring string
func (m Mystring) Say () {
fmt.Println("自定义标准类型")
}
//go语言的多态来实现
func Whosay(i Personer) {
i.Say()
}
func main() {
sxxxx := &Studentxxx{name:"张三",score:12}
txxxx := &Teacherxxx{name:"李四",class:"一年级"}
var my Mystring = "ABC"
sxxxx.Say()
txxxx.Say()
my.Say()
//张三 12
//李四 一年级
//自定义标准类型
//go语言实现多态
Whosay(sxxxx)
Whosay(txxxx)
Whosay(my)
//张三 12
//李四 一年级
//自定义标准类型
//练习一下make,创建一个数组
x := make([]Personer,3)
x[0],x[1],x[2] = sxxxx,txxxx,my
for _,value := range x {
value.Say()
}
//张三 12
//李四 一年级
//自定义标准类型
}
2、interface接口实现继承
//定义一个Personer的接口
type Personer interface {
Say()
}
//接口也可以继承,我们这里写了一个Personer1的接口,这个接口继承Personer这个接口,也就是说Personer1
//这个接口也有Say这个方法了,我们同样也为Personer1这个接口定义了自己的方法,Run()
type Personer1 interface {
Personer
Run()
}
定义了结构体
type Personxxxx struct {
name string
class string
age int
}
定义一个函数
//go语言的多态来实现
func Whosay(i Personer) {
i.Say()
}
为继承的接口定义方法
func (s2 *Personxxxx) Say() {
fmt.Println("接口的继承测试1")
}
func (s2 *Personxxxx) Run() {
fmt.Println("接口的继承测试2")
}
p2 := &Personxxxx{name:"p2222",class:"二年级",age:12}
p2.Say()
p2.Run()
//接口的继承测试1
//接口的继承测试2
Whosay(p2)
//接口的继承测试1
3、if格式的类型判断
package main
import (
"fmt"
)
//接口类型判断
//定义一个空接口
type Niler interface {
}
type PersonTest struct {
name string
age int
}
func main() {
//定义一个接口类型的切片
list := make([] Niler,3)
list[0] = 1
list[1] = "hello"
list[2] = PersonTest{name:"erBi",age:12}
for k,v := range list {
//类型断言,返回的两个参数,一个是value,一个是ok,value是变量的值,ok是返回的布尔值
//comma-ok断言
//这里的例子就是通过上面的返回值v来判断v的类型,如果v的类型为int。则ok为true
_,ok := v.(int)
if ok {
fmt.Println(k,v,"数字")
} else if _,ok := v.(string);ok{
fmt.Println(k,v,"字符串")
} else if value,ok := v.(PersonTest);ok {
fmt.Println(value.name,"结构体")
} else {
fmt.Println("错误的数据类型")
}
}
//0 1 数字
//1 hello 字符串
//erBi 结构体
}
4、switch的类型判断

浙公网安备 33010602011771号