【go语言之切片】

go语言之切片

  • 概述
  • 操作切片
    • 填充
      • append
      • 下标index
    • 截取
    • 扩容

概述

切片是golang中常用的数据类型,是一段连续的内存.
看一下go源码中的定义:

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

这里的array就是底层数组首地址的指针,len和cap都是int,是这个切片的长度和容量.

主要的用法有

s := make([]int,5,10) // 第一种 len 5 cap 10
var s []int // 第二种 len 0 cap 0
s := []int{} // 第三种  len 0 cap 0
s := []int{10} // 第三种 len 1 cap 1
c3 := new([]int) // 第四种 len 0 cap 0

注意这几个用法的,len和cap。对于切片而言,len是已经开辟的内存,是可以正常的操作,但是对于超过len的切片的操作,是会导致越界的panic。示例:

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

	// 导致panic!
	c2[7] = 10

	// 提前填充那么不会
	c2 = append(c2, []int{1, 2, 3}...) 
	c2[7] = 10
	fmt.Printf("c2:%v\n", c2) // 输出 c2:[0 0 0 0 0 1 2 10]
}

操作切片

填充

append

append就是在元素的后面去追加元素,示例

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

    // 填充单个元素
	c2 = append(c2, 1)
    
    // 也填充切片
	c2 = append(c2, []int{1, 2}...)
	fmt.Printf("c2:%v\n", c2) // c2:[0 0 0 0 0 1 1 2]
}

下标index

就是通过下标的方法更改指定下标的元素,注意需要在当前len的范围之内,还是以上面的为例:

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

	c2[4] = 1 //不能超过4
	fmt.Printf("c2:%v\n", c2) // c2:[0 0 0 0 1]
}

截取

可以通过[:]的方法来获取进行截取,对象可以是切片也可以是一个数组,示例:

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

	c3 := c2[1:2:7]

	fmt.Printf("c2:%p c3:%p len:%v cap:%v\n", c2, c3, len(c3), cap(c3)) // c2:0x14000130000 c3:0x14000130008 len:1 cap:6
}

和上面一样,先通过make申明出一个切片,然后通过c2获取到一个c3,需要注意的是这里的c3的len是1,因为是通过c2的第一位到第二位,注意是左闭右开,所以len是1。然后:7是截止到c2第7位下标,所以cap=7-1=6。
同时因为int是一个字节,8位,所以c2的地址是0x14000130000,c3的地址是0x14000130008.在c2的基础上增加了8位。
同时需要注意的是因为是在原有的基础上衍生,所以c3的cap是不能超过原来的切片的cap,不然可能会引发panic,如下

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

	c3 := c2[1:2:11] //  引发panic. runtime error: slice bounds out of range [::11] with capacity 10
}

需要注意的是切片引用的是底层的数组,因此,对切片的更改会影响到底层的数组,这个是需要注意的

package main

import "fmt"

func main() {
	c2 := make([]int, 5, 10)

	c3 := c2[1:3:10] //  runtime error: slice bounds out of range [::11] with capacity 10
	c4 := c2[1:3:10] //  runtime error: slice bounds out of range [::11] with capacity 10
	c4[1] = 1

	fmt.Printf("c2:%v c3:%v c4:%v\n", c2, c3, c4) // c2:[0 0 1 0 0] c3:[0 1] c4:[0 1]
}

可以看到c4的更改,影响到了c3和c2,因此在对slice进行修改的时候,需要注意会不会影响到原有的底层数组。

扩容

当append的操作的数量超过了当前slice的cap上限,就会触发扩容操作。如图:

package main

import "fmt"

func main() {
	c2 := make([]int, 0, 1)

	fmt.Printf("len:%v cap:%v\n", len(c2), cap(c2)) // len:0 cap:1

	c2 = append(c2, 1)
	c2 = append(c2, 2)
	fmt.Printf("len:%v cap:%v\n", len(c2), cap(c2)) // len:2 cap:2

}

从上面可以看出,当添加了2个元素以后,cap从1变成了2。

看一下。扩容的源码在/src/runtime/slice.go中的growslice方法,当前go的版本是go.1.19.1。

// growslice handles slice growth during append.
// It is passed the slice element type, the old slice, and the desired new minimum capacity,
// and it returns a new slice with at least that capacity, with the old data
// copied into it.
// The new slice's length is set to the old slice's length,
// NOT to the new requested capacity.
// This is for codegen convenience. The old slice's length is used immediately
// to calculate where to write new values during an append.
// TODO: When the old backend is gone, reconsider this decision.
// The SSA backend might prefer the new length or to return only ptr/cap and save stack space.
func growslice(et *_type, old slice, cap int) slice {
	if raceenabled {
		callerpc := getcallerpc()
		racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, abi.FuncPCABIInternal(growslice))
	}
	if msanenabled {
		msanread(old.array, uintptr(old.len*int(et.size)))
	}
	if asanenabled {
		asanread(old.array, uintptr(old.len*int(et.size)))
	}

	if cap < old.cap {
		panic(errorString("growslice: cap out of range"))
	}

	if et.size == 0 {
		// append should not create a slice with nil pointer but non-zero len.
		// We assume that append doesn't need to preserve old.array in this case.
		return slice{unsafe.Pointer(&zerobase), old.len, cap}
	}

	newcap := old.cap
	doublecap := newcap + newcap
	if cap > doublecap {
		newcap = cap
	} else {
		const threshold = 256
		if old.cap < threshold {
			newcap = doublecap
		} else {
			// Check 0 < newcap to detect overflow
			// and prevent an infinite loop.
			for 0 < newcap && newcap < cap {
				// Transition from growing 2x for small slices
				// to growing 1.25x for large slices. This formula
				// gives a smooth-ish transition between the two.
				newcap += (newcap + 3*threshold) / 4
			}
			// Set newcap to the requested cap when
			// the newcap calculation overflowed.
			if newcap <= 0 {
				newcap = cap
			}
		}
	}

	var overflow bool
	var lenmem, newlenmem, capmem uintptr
	// Specialize for common values of et.size.
	// For 1 we don't need any division/multiplication.
	// For goarch.PtrSize, compiler will optimize division/multiplication into a shift by a constant.
	// For powers of 2, use a variable shift.
	switch {
	case et.size == 1:
		lenmem = uintptr(old.len)
		newlenmem = uintptr(cap)
		capmem = roundupsize(uintptr(newcap))
		overflow = uintptr(newcap) > maxAlloc
		newcap = int(capmem)
	case et.size == goarch.PtrSize:
		lenmem = uintptr(old.len) * goarch.PtrSize
		newlenmem = uintptr(cap) * goarch.PtrSize
		capmem = roundupsize(uintptr(newcap) * goarch.PtrSize)
		overflow = uintptr(newcap) > maxAlloc/goarch.PtrSize
		newcap = int(capmem / goarch.PtrSize)
	case isPowerOfTwo(et.size):
		var shift uintptr
		if goarch.PtrSize == 8 {
			// Mask shift for better code generation.
			shift = uintptr(sys.Ctz64(uint64(et.size))) & 63
		} else {
			shift = uintptr(sys.Ctz32(uint32(et.size))) & 31
		}
		lenmem = uintptr(old.len) << shift
		newlenmem = uintptr(cap) << shift
		capmem = roundupsize(uintptr(newcap) << shift)
		overflow = uintptr(newcap) > (maxAlloc >> shift)
		newcap = int(capmem >> shift)
	default:
		lenmem = uintptr(old.len) * et.size
		newlenmem = uintptr(cap) * et.size
		capmem, overflow = math.MulUintptr(et.size, uintptr(newcap))
		capmem = roundupsize(capmem)
		newcap = int(capmem / et.size)
	}

	// The check of overflow in addition to capmem > maxAlloc is needed
	// to prevent an overflow which can be used to trigger a segfault
	// on 32bit architectures with this example program:
	//
	// type T [1<<27 + 1]int64
	//
	// var d T
	// var s []T
	//
	// func main() {
	//   s = append(s, d, d, d, d)
	//   print(len(s), "\n")
	// }
	if overflow || capmem > maxAlloc {
		panic(errorString("growslice: cap out of range"))
	}

	var p unsafe.Pointer
	if et.ptrdata == 0 {
		p = mallocgc(capmem, nil, false)
		// The append() that calls growslice is going to overwrite from old.len to cap (which will be the new length).
		// Only clear the part that will not be overwritten.
		memclrNoHeapPointers(add(p, newlenmem), capmem-newlenmem)
	} else {
		// Note: can't use rawmem (which avoids zeroing of memory), because then GC can scan uninitialized memory.
		p = mallocgc(capmem, et, true)
		if lenmem > 0 && writeBarrier.enabled {
			// Only shade the pointers in old.array since we know the destination slice p
			// only contains nil pointers because it has been cleared during alloc.
			bulkBarrierPreWriteSrcOnly(uintptr(p), uintptr(old.array), lenmem-et.size+et.ptrdata)
		}
	}
	memmove(p, old.array, lenmem)

	return slice{p, old.len, newcap}
}

这里主要说一下扩容规则,首先入参.et 是当前的slice的基本数据类型,
old就是扩容前的slice,然后cap是扩容后需要的容量,当前扩容不一样真正是这个容量,这个我们下面说:

1 所需容量大于当前容量的2倍,这个时候没的说,直接用所需的容量。
2 如果所需容量没有到当期容量的2倍,那么当前的容量少于254,那么直接翻倍。
如果当前的容量已经超过了254,那么每次扩容newcap += (newcap + 3*threshold) / 4,大概是1.25-2之间,算是一个平滑的增加。

然后接下来swtch case这里就是对新的容量进行编译器上面的优化,因为要开始分配内存。
然后就是申明一个p的指针,然后调用mallocgc去申请内存,然后将p的指针,就的切片的长度已经新的容量赋值给一个新的slice,然后返回回去。

你可能感兴趣的:(golang)