douhai9043 2017-06-08 23:55
浏览 59
已采纳

append()如何在导致这种情况的幕后工作?

I'm pretty new to Go and trying to track down a bug in my codebase. In the process I've distilled the problem down to a single call to append(), but can't figure out why it's behaving the way it is...

func main() {
    foo := []string{"a", "b", "c"}
    fmt.Printf("before: %v
", foo)

    i := 0
    noop(append(foo[:i], foo[i+1:]...)) // -- call append, but do nothing with the result
    fmt.Printf(" after: %v
", foo)
}

func noop(a interface{}) {} // -- avoid "evaluated but not used" errors

Try it here

So, what the heck is really going on here?

  • 写回答

3条回答 默认 最新

  • doushizhou4477 2017-06-09 00:05
    关注

    append(foo[:i], foo[i+1:]...) does the following:

    1. It takes the foo[:i] slice, which is foo[:0] and basically a slice with length 0 and capacity (at least) 3.

    2. As soon as the capacity is enough to append the values - the underlying array is reused

    3. You write b and c into the indexes 0 and 1 correspondingly of the underlying array.

    Then you check the foo variable that uses the underlying array we just modified and that contains the b c c values.

    Compare with the following:

    noop(append(foo[:i], "a", "a", "a", "a", "a"))
    

    Here the list of values to append is longer than the current capacity. So the runtime allocates a new underlying array. And you don't mutate the foo. https://play.golang.org/p/RooYG_p9Z8

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

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi