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存储在连续内存上:
- 随机访问很快,适合用下标访问,缓存命中率会高。
- 动态扩容时会涉及到内存拷贝和开辟新内存,会带来gc压力、内存碎片化。
- 如果知道所需空间,提前分配cap是很好的。
- 新、老 slice 共用底层数组,对底层数组的更改都会影响到彼此。
- 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
}