alipay域名网站,软件开发专业知识技能,cps网站建设,做网站放广告切片是基于数组实现的#xff0c;它的底层是数组#xff0c;可以理解为对 底层数组的抽象。
源码包中src/runtime/slice.go 定义了slice的数据结构#xff1a;
type slice struct {array unsafe.Pointerlen intcap int
}slice占用24个字节
array: 指向底层数组的指针…切片是基于数组实现的它的底层是数组可以理解为对 底层数组的抽象。
源码包中src/runtime/slice.go 定义了slice的数据结构
type slice struct {array unsafe.Pointerlen intcap int
}slice占用24个字节
array: 指向底层数组的指针占用8个字节
len: 切片的长度占用8个字节
cap: 切片的容量cap 总是大于等于 len 的占用8个字节
slice有4种初始化方式
// 初始化方式1直接声明
var slice1 []int// 初始化方式2使用字面量
slice2 : []int{1, 2, 3, 4}// 初始化方式3使用make创建slice
slice3 : make([]int, 3, 5) // 初始化方式4: 从切片或数组“截取”
slcie4 : arr[1:3]通过一个简单程序看下slice初始化调用的底层函数
package mainimport fmtfunc main() {slice : make([]int, 0)slice append(slice, 1)fmt.Println(slice, len(slice), cap(slice))
}通过 go tool compile -S test.go | grep CALL 得到汇编代码
0x0042 00066 (test.go:6) CALL runtime.makeslice(SB)
0x006d 00109 (test.go:7) CALL runtime.growslice(SB)
0x00a4 00164 (test.go:8) CALL runtime.convTslice(SB)
0x00c0 00192 (test.go:8) CALL runtime.convT64(SB)
0x00d8 00216 (test.go:8) CALL runtime.convT64(SB)
0x0166 00358 ($GOROOT/src/fmt/print.go:274) CALL fmt.Fprintln(SB)
0x0180 00384 (test.go:5) CALL runtime.morestack_noctxt(SB)
0x0079 00121 (autogenerated:1) CALL runtime.efaceeq(SB)
0x00a0 00160 (autogenerated:1) CALL runtime.morestack_noctxt(SB)初始化slice调用的是runtime.makeslicemakeslice函数的工作主要就是计算slice所需内存大小然后调用mallocgc进行内存的分配
所需内存大小 切片中元素大小 * 切片的容量
func makeslice(et *_type, len, cap int) unsafe.Pointer {mem, overflow : math.MulUintptr(et.size, uintptr(cap))if overflow || mem maxAlloc || len 0 || len cap {// NOTE: Produce a len out of range error instead of a// cap out of range error when someone does make([]T, bignumber).// cap out of range is true too, but since the cap is only being// supplied implicitly, saying len is clearer.// See golang.org/issue/4085.mem, overflow : math.MulUintptr(et.size, uintptr(len))if overflow || mem maxAlloc || len 0 {panicmakeslicelen()}panicmakeslicecap()}return mallocgc(mem, et, true)
}本文节选于Go合集《Go语言面试题精讲》GOLANG ROADMAP 一个专注Go语言学习、求职的社区。