(三)golang数组和切片 源码分析 - Go语言中文社区

(三)golang数组和切片 源码分析


1、数组

golang中的数组是一种由固定长度和固定对象类型所组成的数据类型。例如下面:

var a [4]int

a是一个拥有4个int类型元素的数组。当a一旦被声明之后,元素个数就被固定了下来,在a这个变量的生命周期之内,元素个数不会发生变化。而此时a的类型就是[4]int,如果同时存在一个b变量,为[5]int。即便两个变量仅仅相差一个元素,那么在内存中也占据着完全不同的地址分配单元,a和b就是两个完全不同的数据类型。在golang中,数组一旦被定义了,那么其内部的元素就完成了初始化。也就是时候a[0]等于0。
在golang当中,一个数组就是一个数据实体对象。在golang当使用a时,就代表再使用a这个数组。而在C中,当使用a时,则代表着这个数组第一个元素的指针。

2、切片

letters := []string{"a", "b", "c", "d"}

数组声明时候方括号内需要写明数组的长度或者使用(...)符号自动计算长度,切片不需要指定数组的长度。比较规范的声明方式是使用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)

结果是:

[1 2 3 4]

[4 5 6 7]

[1 2 3 100]

[100 5 6 7]

从概念上看,切片像是一个结构体,包含了三个元素:

1、一个指向数组中切片指定的开始位置;

2、长度,即切片的长度,通过内置函数len获得;

3、最大长度,即切片的最大容量,通过内置函数cap获得。

如果len比cap还大,那么就会触发运行时异常。

golang提供append函数来添加元素,当使用append函数时,append函数会判断目的切片是否具有剩余空间,如果没有剩余空间,则会自动扩充两倍空间。

golang提供copy用于将内容从一个数组切片复制到另一个数组切片。如果加入的两个数组切片不一样大,就会按其中较小的那个数组切片的元素个数进行复制。
slice1 := []int{1, 2, 3, 4, 5} 
slice2 := []int{5, 4, 3} 

copy(slice2, slice1) // 只会复制slice1的前3个元素到slice2中 
copy(slice1, slice2) // 只会复制slice2的3个元素到slice1的前3个位置

切片源码解析

源码位置:https://github.com/golang/go/blob/master/src/runtime/slice.go

切片数据结构

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

切片的结构体由3部分构成,Pointer 是指向一个数组的指针,len 代表当前切片的长度,cap 是当前切片的容量。cap 总是大于等于 len 的。

创建切片

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)
}

切片增长

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,于是扩容的时候就翻倍增加容量。
    //一旦元素个数超过 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}
}

切片详解

http://www.jianshu.com/p/030aba2bff41

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/6b0422621c15
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-09 22:17:24
  • 阅读 ( 1092 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢