duandou8457 2014-03-20 11:49
浏览 57
已采纳

如果切片的大小超过数组的大小,切片的元素将存储在哪里?

I create a slice from the array OrgArray as follows

orgArray:=[3] string{"00","01","02"}
s := orgArray[:2]
s = append(s,"03")
s = append(s,"04")

Where 's' is my slice I built up on the array 'orgArray'

If I print the size of the s and orgArray

fmt.Println(s) //[00 01 03 04]
fmt.Println(len(s),cap(s)) //4 6
fmt.Println(len(orgArray),cap(orgArray)) //3 3

len(s) is 4 but len(orgArray) is only 3 why?

Where is the extra elements of slice is storing while appending?

  • 写回答

3条回答 默认 最新

  • duanfangbunao36970 2014-03-20 12:08
    关注

    The Go Programming Language Specification

    Appending to and copying slices

    If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.

    For additional details on how the append built-in function works, read this blog post:

    Arrays, slices (and strings): The mechanics of 'append'

    Also, see this StackOverflow answer, which illustrates the reallocation capacity calculation:

    append complexity

    For example,

    package main
    
    import "fmt"
    
    func main() {
        orgArray := [3]string{"00", "01", "02"}
        fmt.Println("orgArray:", &orgArray[0], len(orgArray), orgArray)
        s := orgArray[:2]
        fmt.Println("       s:", &s[0], len(s), cap(s), s)
        s = append(s, "03")
        fmt.Println("       s:", &s[0], len(s), cap(s), s)
        s = append(s, "04")
        fmt.Println("       s:", &s[0], len(s), cap(s), s)
        fmt.Println("orgArray:", &orgArray[0], len(orgArray), orgArray)
    }
    

    Output:

    orgArray: 0x1052f2c0 3 [00 01 02]
           s: 0x1052f2c0 2 3 [00 01]
           s: 0x1052f2c0 3 3 [00 01 03]
           s: 0x1051a120 4 6 [00 01 03 04]
    orgArray: 0x1052f2c0 3 [00 01 03]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行