十八、Go 语言 – 数据类型 interface

十八、Go 语言 – 数据类型 interface

很多教程都把 interface 翻译成接口,类似于 Java 但我觉得还是把它称之为一种数据类型,它类似于 Java 中的 Object

interface 把所有的具有共性的方法定义在一起, 任何其他类型只要实现了这些方法就是实现了这个 interface

我们可以这么理解, Go 语言没有基类,如果有那么就是

1
interface {}  

任何一个 inteface 都是这个基类的子类,因为它们都可以向上一路转换到 interface{}

比如说

1
2
3
interface add  {
add()
}

是 的子类

语法

Go 语言定义 interface 的语法格式如下

1
2
3
4
5
6
7
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}

如果一个 结构体 struct 实现了一个 interface 中所有的方法,那么我们就可以说这个结构体实现了这个 interface

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 定义结构体 */
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] {
/* 方法实现*/
}

范例

下面的范例,我们定义了一个 interface Phone 和实现了 Phone interface 的结构体 NokiaPhone

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

import (
"fmt"
)

type Phone interface {
call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
fmt.Println("I am iPhone, I can call you!")
}

func main() {
var phone Phone

phone = new(NokiaPhone)
phone.call()

phone = new(IPhone)
phone.call()

}

这个范例中,我们定义了一个 interface Phone,里面有一个方法 call()

然后我们在 main 函数里面定义了一个 Phone 类型变量,并分别为之赋值为 NokiaPhone 和 IPhone

然后调用call()方法

编译运行以上范例,输出结果如下

1
2
3
$ go run main.go
I am Nokia, I can call you!
I am iPhone, I can call you!