Golang中slice总结

142 阅读1分钟

slice与array

定义slice:

var s []int      
s := make([]int, len, cap)

定义array

//数组在方括号中设置长度
var a [length]int

slice type

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

slice vs array

  • array 需指明⻓度,⻓度为常量且不可改变
  • array ⻓度为其类型中的组成部分
  • array 在作为函数参数的时候会产生 copy
  • golang 所有函数参数都是值传递

image.png

image.png

在go中,数组长度也是类型的组成部分

image.png

growslice

  • 当 cap < 1024 的时候,每次 *2
  • 当 cap >= 1024 的时候,每次 * 1.25
  • 特别的,下面这种情况len和cap各为3
var s []int
s = append(s, 0, 1, 2)

append slice

  • 当 cap < 1024 的时候,每次 *2
  • 当 cap >= 1024 的时候,每次 * 1.25
  • 预先分配内存可以提升性能
  • 直接使用 index 赋值而非 append 可以提升性能

slice的坑

  • slice func call,slice为参数
    • 如果没有发生扩容,修改在原来的内存中
    • 如果发生了扩容,修改会在新的内存中 image.png
  • nil slice
    • 使用 []Type{} 或者 make([]Type) 初始化后,slice 不为 nil
    • 使用 var x []Type 后,slice 为 nil