dqcj32855 2016-04-27 13:12
浏览 34
已采纳

将引用类型为“ slice”的变量分配给另一个变量,为什么它们不同时更改?

anotherSlice := theSlice
anotherSlice = append(anotherSlice, newEle)
fmt.Println(len(anotherSlice) == len(theSlice))

This snippet will output false. Why?

And here are some other experiments:

package main

import "fmt"

func main() {
    theSlice := []int{3,3,2,5,12,43}
    anotherSlice := theSlice
    fmt.Println(anotherSlice[3], theSlice[3])
    anotherSlice[3] = anotherSlice[3]+2
    fmt.Println(anotherSlice[3], theSlice[3])
    anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
    fmt.Println(len(anotherSlice),len(theSlice))
}

The output is like below:

5 5
7 7
5 6

Program exited.
  • 写回答

2条回答 默认 最新

  • dousi1097 2016-04-27 13:18
    关注

    Whenever appended slice anotherSlice has no capacity for the new element, append function creates new slice and returns it. Since then the slices anotherSlice and theSlice are different - they are backed by separate arrays.

    Reslicing slice with a shorter length anotherSlice[:3] has no impact on the original capacity of the slice.

    The following line:

    anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
    

    cuts out fourth (index 3) element. Because anotherSlice[:3] has capacity to hold all elements of anotherSlice[4:] no new allocation happens and therefore both slices are modified.

    package main
    
    import (
            "fmt"
    )   
    
    func main() {
            x := []int{1, 2, 3, 4, 5, 6}
            fmt.Println(cap(x[:3]) >= len(x[:3])+len(x[4:]))
            y := append(x[:3], x[4:]...)
            fmt.Println(x, y)
    }
    

    <kbd>Playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?