douchao1957 2016-05-18 14:21
浏览 32
已采纳

在保持切片的同时生长切片

I have been experimenting with slices. Here is an example program

for n := 1; n <= 10; n++ {
    a := make([]int, 0)
    for j := 0; j < n; j++ {
        a = append(a, 0)
    }
    b := a[:1]
    a = append(a, 0)
    a[0] = 1
    fmt.Println(n, b[0])
}

The output is

1 0
2 0
3 1
4 0
5 1
6 1
7 1
8 0
9 1
10 1

I understand what is going on here. The line a = append(a, 0) allocates a new array if the old array has insufficient length, and the new array has twice the length as the original. Therefore if n is a power of 2, the line

a[0] = 1

will not change the array backed by b as a new array will have been allocated in the line before.

However I could not find an explicit statement in the documentation that the newly allocated array always has twice the length. Does this mean that my code is implementation dependent? Is it bad practice to store a slice of another slice in a variable in this way, or should I just do a[j:k] every time a subslice is needed?

  • 写回答

2条回答 默认 最新

  • donglun1918 2016-05-18 15:19
    关注

    You already know the answer.

    • It is implementation dependent
    • It is bad practice to sub-slice to a var if you are changing an underlying array/slice
    • You better off to use sub-slicing explicitly whenever needed - it's cheap.

    Good question though. Thanks for sharing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析