[toc]
<font size=6>golang內(nèi)置類型的底層數(shù)據(jù)結(jié)構(gòu)
<font size=5>slice切片 </font>
//[]int16
type = struct []int16 {
int16 *array;
int len;
int cap;
//[]byte
type = struct []uint8 {
uint8 *array;
int len;
int cap;
}
- slice中 array 是一個(gè)指針,它指向的是一個(gè)Array
- len 代表的是這個(gè)slice中的元素長度
- cap 是slice的容量
<font size=4>特性</font>
slice的Array存儲在連續(xù)內(nèi)存上:
- 隨機(jī)訪問很快丑孩,適合用下標(biāo)訪問摄悯,緩存命中率會高朽缎。
- 動態(tài)擴(kuò)容時(shí)會涉及到內(nèi)存拷貝和開辟新內(nèi)存稠集,會帶來gc壓力撮执、內(nèi)存碎片化薄翅。
- 如果知道所需空間沙兰,提前分配cap是很好的。
- 新翘魄、老 slice 共用底層數(shù)組鼎天,對底層數(shù)組的更改都會影響到彼此。
- append可以掰斷新老slice共用底層數(shù)組的關(guān)系暑竟。(不理解斋射?可以參考擴(kuò)容原理)
<font size=5>string字符串</font>
//string
type = struct string {
uint8 *str;
int len;
}
<font size=5>map</font>
//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;
} *
<font size=5>interface接口類型</font>
//interface
type = struct runtime.eface {
runtime._type *_type;
void *data;
}