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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)