接口
接口是一种类型, 约定了要实现的方法列表, 可实现鸭子类型, 即看起来像鸭子, 叫起来像鸭子, 就是鸭子
定义接口
type Player interface {
Runner // 接口嵌套
Jumper
}
type Runner interface {
run(speed int) (res string, canRun bool)
}
type Jumper interface {
jump(height int) (res string, canJump bool)
}
结构体实现接口
type Pig struct {
name string
}
func (p Pig) run(speed int) (res string, canRun bool) {
return p.name + "'s speed is " + fmt.Sprint(speed) + "km/h", true
}
func (p Pig) jump(height int) (res string, canJump bool) {
return p.name + " can jump " + fmt.Sprint(height) + "m hight", true
}
type Dog struct {
name string
}
func (p Dog) run(speed int) (res string, canRun bool) {
return p.name + "'s speed is " + fmt.Sprint(speed) + "km/h", true
}
func (p Dog) jump(height int) (res string, canJump bool) {
return p.name + " can jump " + fmt.Sprint(height) + "m hight", true
}
接口应用
pig := Pig{name: "Peggy"}
runRes, canRun := pig.run(30)
if canRun {
fmt.Println(runRes) // Peggy's speed is 30km/h
}
var player Player
player = pig
jumpRes, canJump := player.jump(2)
if canJump {
fmt.Println(jumpRes) // Peggy can jump 2m hight
}
dog := Dog{name: "Wangcai"}
player = dog
runRes, canRun = dog.run(50)
if canRun {
fmt.Println(runRes) // Wangcai's speed is 50km/h
}
内嵌结构体实现部分接口
// 洗剪吹
type WashCutBlow interface {
wash()
cut()
blow()
}
type Blower struct {
}
func (b Blower) blow() {
fmt.Println("I can blow~")
}
// 托尼老师
type TeacherTony struct {
name string
Blower
}
func (t TeacherTony) wash() {
fmt.Println("I can wasg~")
}
func (t TeacherTony) cut() {
fmt.Println("I can cut~")
}
func main () {
// 内嵌结构体实现部分接口
var wcb WashCutBlow
teacherTony := TeacherTony{name: "Tony"}
wcb = teacherTony
fmt.Println(wcb)
wcb.blow() // I can blow~
}
空接口
类似ts中的any
// 空接口
type EmptyInterface interface{}
var x EmptyInterface
x = 1
fmt.Printf("type: %T, value: %#v \n", x, x) // type: int, value: 1
x = "a"
fmt.Printf("type: %T, value: %#v \n", x, x) // type: string, value: "a"
x = 'a'
fmt.Printf("type: %T, value: %#v \n", x, x) // type: int32, value: 97
// 空接口应用, 类似ts中的any
person := make(map[interface{}]interface{})
person["age"] = 18
person[false] = 1
fmt.Printf("type: %T, value: %#v \n", person, person) // type: map[interface {}]interface {}, value: map[interface {}]interface {}{false:1, "age":18}
类型断言
类似js中的tyeof
value, ok := x.(string)
if ok {
fmt.Printf("value: %#v \n", value)
} else {
fmt.Println("x is not string") // x is not string
}
x = "b"
value, ok = x.(string)
if ok {
fmt.Printf("value: %#v \n", value) // value: "b"
} else {
fmt.Println("x is not string")
}