golang底层数据结构

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的赋值、以值作为函数参数时只拷贝1个指针、2个int

特性

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

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

string字符串

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

string的底层结构因平台而异,并且在未来的版本更新中可能发生改变。
对string的赋值、以值作为函数参数时只拷贝1个指针、1个int

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;
}

//interface
//有方法
type = struct runtime.iface {
    runtime.itab *tab;
    void *data;
}

// layout of Itab known to compilers
// allocated in non-garbage-collected memory
// Needs to be in sync with
// ../cmd/compile/internal/gc/reflect.go:/^func.dumptypestructs.
type itab struct {
	inter *interfacetype
	_type *_type
	hash  uint32 // copy of _type.hash. Used for type switches.
	_     [4]byte
	fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}

// Needs to be in sync with ../cmd/link/internal/ld/decodesym.go:/^func.commonsize,
// ../cmd/compile/internal/gc/reflect.go:/^func.dcommontype and
// ../reflect/type.go:/^type.rtype.
type _type struct {
	size       uintptr
	ptrdata    uintptr // size of memory prefix holding all pointers
	hash       uint32
	tflag      tflag
	align      uint8
	fieldalign uint8
	kind       uint8
	alg        *typeAlg
	// 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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值