接口和反射

接口的定义方式

1
2
3
4
type Namer interface {
Method1(param_list) return_type
Method2(param_list) return_type
}

接口相对于其他面向对象的语言,是 Go 中的多态的表现。具体代码展示如下:

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
package main

import "fmt"

type Shaper interface {
Area() float32
}

type Square struct {
side float32
}

func (sq *Square) Area() float32 {
return sq.side * sq.side
}

type Rectangle struct {
length, width float32
}

func (r Rectangle) Area() float32 {
return r.length * r.width
}

func main() {

r := Rectangle{5, 3} // Area() of Rectangle needs a value
q := &Square{5} // Area() of Square needs a pointer
// shapes := []Shaper{Shaper(r), Shaper(q)}
// or shorter
shapes := []Shaper{r, q}
fmt.Println("Looping through shapes for area ...")
for n, _ := range shapes {
fmt.Println("Shape details: ", shapes[n])
fmt.Println("Area of this shape is: ", shapes[n].Area())
}
}

接口嵌套接口

一个接口可以包含一个或多个其他的接口,这相当于直接将这些内嵌接口非方法列举在外层接口中一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type ReadWrite interface {
Read(b Buffer) bool
Write(b Buffer) bool
}

type Lock interface {
Lock()
UnLock()
}

type File interface {
ReadWrite
Lock
Close()
}

接口 File 包含了 ReadWrite 和 Lock 的所有方法,同时还额外有一个 Close() 方法。

反射

1
2
3
4
if v, ok := varI.(T); ok {
Process(v)
return
}

type-switch

1
2
3
4
5
6
7
8
9
10

switch t := areaIntf(type) {
case type1:
Process1(t)
case type2:
Process2(t)
default:
Process(t)
}

鸭子模型

主要表现为接口和动态类型,这意味着对象可以根据提供的方法被处理而忽略实际的类型,类似于 Python 中的鸭子模型(duck typing):

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 IDuck interface {
Quack()
Walk()
}

func DuckDance(duck IDuck) {
for i := 1; i <= 3; i++ {
duck.Quack()
duck.Walk()
}
}

type Bird struct {
// ...
}

func (b *Bird) Quack() {
fmt.Println("I am quacking!")
}

func (b *Bird) Walk() {
fmt.Println("I am walking!")
}

func main() {
b := new(Bird)
DuckDance(b)
}

相对应的 Python 版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Duck:
def quack(self):
print "Quaaaaack..."
def feathers(self):
print "The Duck has feathers."

class Person:
def quack(self):
print "Person is not a duck"
def feathers(self):
print "The person takes a feather from the ground and shows it."

def in_the_forest(duck):
duck.quack()
duck.feathers()

def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)

game()

接口的提取

提取接口 是非常有用的设计模式,可以减少需要的类型和方法数量。

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
52
53
54
//multi_interfaces_poly.go
package main

import "fmt"

type Shaper interface {
Area() float32
}

type TopologicalGenus interface {
Rank() int
}

type Square struct {
side float32
}

func (sq *Square) Area() float32 {
return sq.side * sq.side
}

func (sq *Square) Rank() int {
return 1
}

type Rectangle struct {
length, width float32
}

func (r Rectangle) Area() float32 {
return r.length * r.width
}

func (r Rectangle) Rank() int {
return 2
}

func main() {
r := Rectangle{5, 3} // Area() of Rectangle needs a value
q := &Square{5} // Area() of Square needs a pointer
shapes := []Shaper{r, q} // 创建一个接口列表 并不关心它是什么类型的。
fmt.Println("Looping through shapes for area ...")
for n, _ := range shapes {
fmt.Println("Shape details: ", shapes[n])
fmt.Println("Area of this shape is: ", shapes[n].Area())
}
topgen := []TopologicalGenus{r, q}
fmt.Println("Looping through topgen for rank ...")
for n, _ := range topgen {
fmt.Println("Shape details: ", topgen[n])
fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank())
}
}

空接口和函数重载

Go 中的函数重载是不被允许的。但是在 Go 中可以通过可变参数 …T 作为函数的最后一个参数来实现。如果我们将 T 变为空接口,那么其实 T 是可以为任何类型的,这样就允许我们传递任何数量任何类型的参数给函数,即为重载的意义:

1
fmt.Printf(format string, a ...interface{})(n int, errno error)

该函数通过枚举 slice 类型来确定所有参数的内容和类型,查看该类型是否实现了 string() 方法,如果有就用来产生输出信息。

高阶函数(类似 Python 中的装饰器)

首先定义一系列的 struct 和 interface。

1
2
3
4
5
6
7
8
9
10
11

type Any interface{}
type Car struct {
Model string
Manufacturer string
BuildYear int
// ...
}

type Cars []*Car

定义函数功能时,可以将函数作为其他函数的参数:

1
2
3
4
5
func (cs Cars) Process(f func(car *Car)) {
for _, c := range cs {
f(c) // Caller
}
}

在上面的基础上,实现一个子函数,并在 Process() 中传入一个闭包执行(这样就可以访问局部切片 cars)

1
2
3
4
5
6
7
8
9
func (cs Cars) FindAll(f func(car *Car) bool) Cars {
cars := make([]*Car, 0)
cs.Process(func(c *Car) {
if f(c) {
cars = append(cars, c)
}
})
return cars
}

实现 Map 功能,产出除 car 对象以外的东西。

1
2
3
4
5
6
7
8
9
func (cs Cars) Map(f func(car *Car) Any) []Any {
result := make([]Any, 0)
ix := 0
cs.Process(func(c *Car){
result[idx] = f(c)
ix++
})
return result
}

这样我们就可以定义以下的查询:

1
2
3
4
allNewBMWs := allCars.Findall(func(car *Car) bool) {
return (car.Manufacturer == "BMW")
}