NOTE

1.10 类型系统

1. 有哪些类型 1.1. 内置类型 1.2. 自定义类型 2. 类型元数据是什么 不管是内置类型哈还是自定义类型都有类型元数据,这些类型元数据共同构成了Go语言的类型系统 不管是内置类型还是自定义类型,都有一个对象头 2.1. 内置类型 内置类型除了对象头之外,还会有额外信息 2.1.1. 举例

Go创建于 更新于 historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 有哪些类型

1.1. 内置类型

int、float、string、slice、mapinterface

1.2. 自定义类型


type T1 int

type T2 struct {
    name string
}
type T3 interface {
    F1()
}

2. 类型元数据是什么

不管是内置类型哈还是自定义类型都有类型元数据,这些类型元数据共同构成了Go语言的类型系统 不管是内置类型还是自定义类型,都有一个对象头

type _type struct {
    size       uintptr
    ptrdata    uintptr
    hash       uint32
    tflag      tflag
    align      uint8
    fieldalign uint8
    kind       uint8
    alg        *typeAlg
    gcdata     *byte
    str        nameOff
    ptrToThis  typeOff
}

2.1. 内置类型

内置类型除了对象头之外,还会有额外信息

2.1.1. 举例

  • slice
type slicetype struct {
    typ   _type
    elem  *_type
}

  • 指针
    typ   _type
    elem  *_type
}

2.2. 自定义类型

  • 多出一个uncommontype
type uncommontype struct {
    pkgpath nameOff//记录类型所在的包路径;
    mcount  uint16 //记录了该类型关联到多少个方法;
    _       uint16 // unused
    moff    uint32 //记录的是这些方法的元数据组成的数组相对于这个uncommontype结构体偏移了多少字节
}

//moff指向的方法元数据
type method struct {
    name nameOff
    mtyp typeOff
    ifn  textOff
    tfn  textOff
}

2.2.1. 举例

type myslice []string
func (ms myslice) Len(){
    fmt.Println(len(ms))
}
func (ms myslice) Cap(){
    fmt.Println(cap(ms))
}