Go-11-基础类型

go源码下载地址

golang的数据类型和数据结构的底层实现

Go的类型系统

Golang的类型分为以下几类:

  1. 命名类型[named (defined) type]具有名称的类型:int,int64,float32,string,bool。这些GO预先声明好了

    通过类型声明(type declaration)创建的所有类型都是命令类型

    1
    2
    3
    var i int 	//named type
    type myInt int //named type
    var b bool //named type

    一个命名类型一定和其他类型不同

  2. 未命名类型(unnamed type):数组,结构体,指针,函数,接口,切片,map,通道都是未命令类型

    1
    2
    3
    []string // unnamed type
    map[string]string // unnamed type
    [10]int // unnamed type

    虽然没有名字,但却有一个类型字面量(type literal)来描述它们由什么构成

  3. 基础类型

    任何类型T都有基础类型

    • 如果T 是预先声明类型:boolean, numeric, or string(布尔,数值,字符串)中的一个,或者是一个类型字面量(type literal),他们对应的基础类型就是T自身。

    • T的基础类型就是T所引用的那个类型的类型声明(type declaration)

基本类型

/src/runtime/type.go 对 type类型进行了定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type _type struct {
size uintptr
ptrdata uintptr // size of memory prefix holding all pointers
hash uint32
tflag tflag
align uint8
fieldAlign uint8
kind uint8
// function for comparing objects of this type
// (ptr to object A, ptr to object B) -> ==?
equal func(unsafe.Pointer, unsafe.Pointer) bool
// gcdata stores the GC type data for the garbage collector.
// If the KindGCProg bit is set in kind, gcdata is a GC program.
// Otherwise it is a ptrmask bitmap. See mbitmap.go for details.
gcdata *byte
str nameOff
ptrToThis typeOff
}

string类型

/src/runtime/string.go 对string类型进行了声明

1
2
3
4
type stringStruct struct {
str unsafe.Pointer
len int
}

参考链接

  1. 深入研究Go(golang) Type类型系统