[toc]

golang内置类型的底层数据结构

slice切片

//[]int16
type = struct []int16 {
    int16 *array;
    int len;
    int cap;

//[]byte
type = struct []uint8 {
    uint8 *array;
    int len;
    int cap;
}
  • slice中 array 是一个指针,它指向的是一个Array
  • len 代表的是这个slice中的元素长度
  • cap 是slice的容量

特性

slice的Array存储在连续内存上:

  1. 随机访问很快,适合用下标访问,缓存命中率会高。
  2. 动态扩容时会涉及到内存拷贝和开辟新内存,会带来gc压力、内存碎片化。
  3. 如果知道所需空间,提前分配cap是很好的。
  4. 新、老 slice 共用底层数组,对底层数组的更改都会影响到彼此。
  5. append可以掰断新老slice共用底层数组的关系。(不理解?可以参考扩容原理)

string字符串

//string
type = struct string {
    uint8 *str;
    int len;
}

map

//map[int16]byte
type = struct hash<int16, uint8> {
    int count;
    uint8 flags;
    uint8 B;
    uint16 noverflow;
    uint32 hash0;
    struct bucket<int16, uint8> *buckets;
    struct bucket<int16, uint8> *oldbuckets;
    uintptr nevacuate;
    runtime.mapextra *extra;
} *

interface接口类型

//interface
type = struct runtime.eface {
    runtime._type *_type;
    void *data;
}