Eli's Blog

1. 静态类型和动态类型

  • 静态类型: static type,即变量声明的时候的类型。
  • 动态类型: concrete type,具体类型,程序运行时系统才能看见的类型
1
2
3
4
var i interface{}   // 静态类型为interface

i = 8 // 动态类型为int
i = "abc" // 动态类型为string

2. 接口组成

  • Type
  • Data

interface

3. 接口细分

3.1 iface: 带有方法的接口

示例:

1
2
3
type Phone interface {
Call()
}

实现源码:

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
// runtime/runtime2.go
// 非空接口
type iface struct {
tab *itab
data unsafe.Pointer
}

// 非空接口的类型信息
type itab struct {
inter *interfacetype // 静态类型
_type *_type // 动态类型
link *itab
bad int32
inhash int32
fun [1]uintptr // 接口方法实现列表,即函数地址列表,按字典序排序
}

// runtime/type.go
// 非空接口类型,接口定义,包路径等。
type interfacetype struct {
typ _type
pkgpath name
mhdr []imethod // 接口方法声明列表,按字典序排序
}
// 接口的方法声明
type imethod struct {
name nameOff // 方法名
ityp typeOff // 描述方法参数返回值等细节
}

实例:

1
2
3
4
5
6
7
8
9
10
11
func GetTty() (*os.File, error) {
var reader io.Reader

tty, err := open.OpenFile("/dev/tty", os.DRWR, 0)
if err != nil {
return nil, err
}

reader = tty // 静态类型为io.Reader, 动态类型变为*os.File
return reader, nil
}

iface

3.2 eface: 不带方法的接口

示例:

1
var i interface{}

实现源码:

1
2
3
4
5
6
// src/runtime/runtime2.go
// 空接口
type eface struct {
_type *_type
data unsafe.Pointer
}

实例:

1
2
3
4
5
6
7
8
9
10
11
func GetTty() (interface{}, error) {
var empty interface{}

tty, err := open.OpenFile("/dev/tty", os.DRWR, 0)
if err != nil {
return nil, err
}

empty = tty
return empty, nil
}

eface