1、數(shù)組
golang中的數(shù)組是一種由固定長度和固定對象類型所組成的數(shù)據(jù)類型。例如下面:
var a [4]int
a是一個擁有4個int類型元素的數(shù)組网严。當a一旦被聲明之后,元素個數(shù)就被固定了下來嗤无,在a這個變量的生命周期之內(nèi)震束,元素個數(shù)不會發(fā)生變化。而此時a的類型就是[4]int当犯,如果同時存在一個b變量垢村,為[5]int。即便兩個變量僅僅相差一個元素嚎卫,那么在內(nèi)存中也占據(jù)著完全不同的地址分配單元嘉栓,a和b就是兩個完全不同的數(shù)據(jù)類型。在golang中拓诸,數(shù)組一旦被定義了侵佃,那么其內(nèi)部的元素就完成了初始化。也就是時候a[0]等于0奠支。
在golang當中趣钱,一個數(shù)組就是一個數(shù)據(jù)實體對象。在golang當使用a時胚宦,就代表再使用a這個數(shù)組。而在C中燕垃,當使用a時枢劝,則代表著這個數(shù)組第一個元素的指針。
2卜壕、切片
letters := []string{"a", "b", "c", "d"}
數(shù)組聲明時候方括號內(nèi)需要寫明數(shù)組的長度或者使用(...)符號自動計算長度您旁,切片不需要指定數(shù)組的長度。比較規(guī)范的聲明方式是使用make轴捎,大致有兩種方式
1鹤盒、只指定長度,這個時候切片長度和容量相同侦副;
2侦锯、同時指定切片的長度和容量。
var s1 = make([]byte, 5)
var s2 = make([]byte, 5, 10)
由于切片是 引用類型 秦驯,因此當引用改變其中元素的值時候尺碰,其他的所有引用都會改變該值。例如
var a = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := a[:4]
s2 := a[3:7]
fmt.Println(s1)
fmt.Println(s2)
s1[3] = 100
fmt.Println(s1)
fmt.Println(s2)
結(jié)果是:
[1 2 3 4]
[4 5 6 7]
[1 2 3 100]
[100 5 6 7]
從概念上看,切片像是一個結(jié)構(gòu)體亲桥,包含了三個元素:
1洛心、一個指向數(shù)組中切片指定的開始位置;
2题篷、長度词身,即切片的長度,通過內(nèi)置函數(shù)len獲得番枚;
3法严、最大長度,即切片的最大容量户辫,通過內(nèi)置函數(shù)cap獲得渐夸。
如果len比cap還大,那么就會觸發(fā)運行時異常渔欢。
golang提供append函數(shù)來添加元素墓塌,當使用append函數(shù)時,append函數(shù)會判斷目的切片是否具有剩余空間奥额,如果沒有剩余空間苫幢,則會自動擴充兩倍空間。
golang提供copy用于將內(nèi)容從一個數(shù)組切片復(fù)制到另一個數(shù)組切片垫挨。如果加入的兩個數(shù)組切片不一樣大韩肝,就會按其中較小的那個數(shù)組切片的元素個數(shù)進行復(fù)制。
slice1 := []int{1, 2, 3, 4, 5}
slice2 := []int{5, 4, 3}
copy(slice2, slice1) // 只會復(fù)制slice1的前3個元素到slice2中
copy(slice1, slice2) // 只會復(fù)制slice2的3個元素到slice1的前3個位置
切片源碼解析
源碼位置:https://github.com/golang/go/blob/master/src/runtime/slice.go
切片數(shù)據(jù)結(jié)構(gòu)
type slice struct {
array unsafe.Pointer
len int
cap int
}
切片的結(jié)構(gòu)體由3部分構(gòu)成九榔,Pointer 是指向一個數(shù)組的指針哀峻,len 代表當前切片的長度,cap 是當前切片的容量哲泊。cap 總是大于等于 len 的剩蟀。
創(chuàng)建切片
func makeslice(et *_type, len, cap int) unsafe.Pointer {
// 所需要分配的內(nèi)存大小
mem, overflow := math.MulUintptr(et.size, uintptr(cap))
// 判斷根據(jù)容量內(nèi)存大小是否超過限制 數(shù)組長度和容量是否合法
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))
// 判斷根據(jù)長度內(nèi)存大小是否超過限制、數(shù)組長度是否合法
if overflow || mem > maxAlloc || len < 0 {
panicmakeslicelen()
}
panicmakeslicecap()
}
return mallocgc(mem, et, true)
}
切片增長
func growslice(et *_type, old slice, cap int) slice {
if raceenabled {
callerpc := getcallerpc()
racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))
}
if msanenabled {
msanread(old.array, uintptr(old.len*int(et.size)))
}
// 如果小于原來的容量大小直接panic
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}
}
//擴容策略
//如果新容量大于原來容量的二倍直接用新容量切威。
//如果原來切片的容量小于1024育特,于是擴容的時候就翻倍增加容量。
//一旦元素個數(shù)超過 1024先朦,那么增長因子就變成 1.25 缰冤,即每次增加原來容量的四分之一。
newcap := old.cap
doublecap := newcap + newcap
if cap > doublecap {
newcap = cap
} else {
if old.len < 1024 {
newcap = doublecap
} else {
// Check 0 < newcap to detect overflow
// and prevent an infinite loop.
for 0 < newcap && newcap < cap {
newcap += newcap / 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 sys.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 == sys.PtrSize:
lenmem = uintptr(old.len) * sys.PtrSize
newlenmem = uintptr(cap) * sys.PtrSize
capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
newcap = int(capmem / sys.PtrSize)
case isPowerOfTwo(et.size):
var shift uintptr
if sys.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)
}
}
memmove(p, old.array, lenmem)
return slice{p, old.len, newcap}
}