4

关于对切片操作导致基底数组变更的问题

 2 years ago
source link: https://studygolang.com/articles/35410
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

关于对切片操作导致基底数组变更的问题

0x25w · 大约3小时之前 · 25 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

s := []int{1, 2, 3, 4, 5} 长度5 容量5 newS := s[a:b]s为基底生成切片时, 长度 b-a 容量 len(s)-a
newS进行append后: 若容量不超 ,那么[]s也会跟着改变 若超了,则[]s不改变,[]newS可视为new出来的一个切片 且容量翻倍直至足够容纳新切片,当超过1000时,变为每次增长25%

package main

import "fmt"

func main() {


}

//    切片基底数组变更
func slice1(){
    //new一个长度5容量5的数组
    slice := []int{10, 20, 30, 40, 50}

    //切片生成新数组,这个数组的长度为3-1=2  容量为len(slice)-1 此处的1是切片开始的位置
    newSlice := slice[1:3]

    //进行append操作,append一次后长度变为3
    newSlice = append(newSlice, 60)

    //由于未超出容量4,因此会导致基底跟随变化
    fmt.Printf("slice: %v\n", slice)
    fmt.Printf("newSlice: %v\n", newSlice)

    //    output:
    //    slice: [10 20 30 60 50]
    //    newSlice: [20 30 60]

}

//    切片基底数组未变更
func slice2(){
    //new一个长度5容量5的数组
    slice := []int{10, 20, 30, 40, 50}

    //切片生成新数组,这个数组的长度为3-1=2  容量为len(slice)-1 此处的1是切片开始的位置
    newSlice := slice[1:3]

    //进行append操作,append一次后长度变为5,但是之前容量只有4,因此容量翻倍变为8
    newSlice = append(newSlice, 60,70,80)

    //由于超出容量4,因此新切片可被视为new出来的,不会导致基底跟随变化
    fmt.Printf("slice: %v\n", slice)
    fmt.Printf("newSlice: %v\n", newSlice)

    //    output:
    //    slice: [10 20 30 40 50]
    //    newSlice: [20 30 60 70 80]
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK