Go interface(接口)

1. 概念

接口是一个或多个方法签名的集合,只有方法声明,没有实现。

只要某个类型拥有该接口的所有方法签名,即算实现了该接口,无需显式声明了哪个接口,这称为 Structural Typing

接口也是一种类型,它是一种抽象类型,空接口 interface {} 类似于 NSObject 这样的万物之主,虽然 Go 中是没有 class 的概念,但 interface 实现了继承多态的效果。

2. 使用

样例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
"fmt"
)

type USB interface {
Name() string
Connecter // 嵌入
}

type Connecter interface {
Connect()
}

type PhoneConnecter struct {
name string
}

func (pc PhoneConnecter) Name() string {
return pc.name
}

func (pc PhoneConnecter) Connect() {
fmt.Println("Connect:", pc.name)
// Disconnected: PhoneConnecter
}

func Disconnect(usb interface{}) {
// ok pattern 进行类型判断
//if pc, ok := usb.(PhoneConnecter); ok {
// fmt.Println("Disconnected:", pc.name)
// return
//}
//fmt.Println("Disconnected.")

// type switch 进行类型判断
switch v := usb.(type) {
case PhoneConnecter:
fmt.Println("Disconnected:", v.name)
// print "Connect: PhoneConnecter"
default:
fmt.Println("Unknown Device")
}
}

func main() {
a := PhoneConnecter{"PhoneConnecter"}
a.Connect()
Disconnect(a)
}

样例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
"fmt"
)

type square struct { r int }

type circle struct { r int }

func (s square) area() int { return s.r * s.r }

func (c circle) area() int { return c.r * 3 }

func main() {
s := square{2}
c := circle{3}
a := [2]interface{}{s, c}
fmt.Println(s, c, a)
// print "{2} {3} [{2} {3}]"

sum := 0
for _, t := range a {
switch v := t.(type) {
case square:
sum += v.area()
case circle:
sum += v.area()
}
}
fmt.Println(sum)
// print "13"
}
您的支持将鼓励我继续创作!
0%