切片是基于数组实现的,它的底层是数组,可以理解为对 底层数组的抽象。
源码包中src/runtime/slice.go 定义了slice的数据结构:
type slice struct {
array unsafe.Pointer
len int
cap 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 main
import "fmt"
func 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.makeslice,makeslice函数的工作主要就是计算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)
}