dongyi2534 2018-02-25 21:30
浏览 80

切片的删除元素会修改原始值

I'm wondering about the following behavior:

sl1 := []int{0, 1, 2, 3, 4, 5}
fmt.Printf("sl1: %v
", sl1)
//Prints sl1: [0 1 2 3 4 5]

idx := 3
sl2 := append(sl1[:idx], sl1[idx+1:]...)
fmt.Printf("sl1: %v
", sl1)
//Prints sl1: [0 1 2 4 5 5] -> strange!
fmt.Printf("sl2: %v
", sl2)
//Prints sl2: [0 1 2 4 5] -> expected!

Looks like append is doing something weird on the original slice pointer. Is this a bug or intended behavior? See also https://play.golang.org/p/EX3eqJz5Q8K

  • 写回答

1条回答 默认 最新

  • doupaimo8288 2018-02-25 21:46
    关注

    A slice consists of a reference to an underlying array, a length, and a capacity (maximum length). sl1[:idx] is a different slice than sl1 (the length is 3 instead of 6), but the underlying array is the same. The append places elements 4 and 5 of sl1 into the array at positions 3 and 4. sl2 is then a slice of length 5, but the underlying array is still the original one referenced by sl1, so when you print sl1, you see that the elements have changed. See https://blog.golang.org/go-slices-usage-and-internals for an explanation of how slices work.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?