douman6245 2018-12-01 16:17
浏览 67
已采纳

追加到新切片会影响原始切片

I have the following code which causes a weird result. I cannot understand why:

func main() {
    var s = []int{2, 3}
    var s1 = append(s, 4)
    var a = append(s1, 5)
    var b = append(s1, 6)
    fmt.Println(s)
    fmt.Println(s1)
    fmt.Println(a)
    fmt.Println(b)
}

This then results in:

[2 3]
[2 3 4]
[2 3 4 6]
[2 3 4 6]

My question is: why a is not [2 3 4 5] but [2 3 4 6]? I know append to b changes a, but how. Is this a bug because I never changed a directly and obviously I don't want this happen?

  • 写回答

1条回答 默认 最新

  • dtv7174 2018-12-02 05:41
    关注

    Keep in mind that a slice is a structure of 3 fields.

    • a pointer to the underlying array
    • length of the slice
    • capacity of the slice

    append() function may either modify its argument in-place or return a copy of its argument with an additional entry, depending on the size and capacity of its input. append() function creates a new slice, if the length the slice is greater than the length of the array pointed by the slice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀