go基础-切片和数组

820人浏览 / 0人评论

切片和数组

type slice struct {
	array unsafe.Pointer
	len   int
	cap   int
}

从切片的结构定义来看,是对底层数组的封装,增加了长度及容量字段

切片创建

使用make创建切片

  • 类型长度*cap是否越界(cap会强制转换成无符号)
  • 类型长度*cap是否超过系统上限
const maxAlloc untyped int = 281474976710656
maxAlloc is the maximum size of an allocation. On 64-bit, it's theoretically possible to allocate 1<<heapAddrBits bytes. On 32-bit, however, this is one less than 1<<32 because the number of bytes in the address space doesn't actually fit in a uintptr.
  • 判断参数是否合法:len非负、len需不大于cap
  • 申请内存

使用数组创建切片

import "fmt"

func main() {
	var array [10]int
	slice := array[3:5]
	fmt.Println(len(slice), cap(slice))
	fmt.Println(&array[3] == &slice[0])
}

2 7
true
  • 对数组进行[start:end:cap]截取操作创建切片,end不能超过数组末尾
  • 切片长度为end-start,即不包含end所在位置
  • 切片容量cap,且不能超过start到数组末尾
  • 创建的切片与数组公用内存
  • start缺省表示从数组首个元素开始,end缺省表示为数组末尾

切片扩容

  • 目标容量是否超过当前容量2倍,是则直接扩容至目标容量
  • 当前容量小于1024,扩容为当前容量2倍
  • 当前容量大于等于1024,增加当前容量/4;直至超过目标容量
  • 根据新的容量申请内存
  • 拷贝原有数据

全部评论