普通网友 2016-03-10 15:22
浏览 14

为什么追加修改通过的切片

How could I iterate through the slice and pass somewhere the slice except the current element? Seems append() function modifies the underlying slice as we could see in documentation. But anyway I still don't know how to reach this.

func main() {
    args := []string{ "2", "3", "8" }

    for i, _ := range args {
        fmt.Println(append(args[:i], args[i+1:]...)) // or pass to function
    }

    fmt.Println(args)
}

result:

[3 8]
[3 8]
[3 8]
[3 8 8] // it is args now

what I expect:

 [3 8]
 [2 8]
 [2 3]

I already saw this Why does append() modify the provided slice? (See example)

but what is the Capacity of the slice is the secret for me, and I dont understand why did I exceed it.

  • 写回答

4条回答 默认 最新

  • dongxian6285 2016-03-10 15:39
    关注

    You can imagine a slice as a struct composed of an array of fixed size and a counter for the number of elements in it. The capacity of the slice is the size of the underlying array, while the lenght of the slice is the counter.

    Append is defined that way : func append(slice []Type, elems ...Type) []Type (godoc), which essentially means that you will be appending the elem variadic argument to the slice argument. If len(elems) + len(slice) > cap(slice), then udnerlying array will need to be changed for a bigger one (with a bigger capacity), which mean (in go) a new slice (hence the return parameter).

    In your case, you didn't exceeded the capacity of the slice. You just modified its content.

    One simple (albeit slightly ugly) trick would be to nested two appends to an empty slice :

    package main
    
    import "fmt"
    
    func main() {
        args := []string{ "2", "3", "8" }
    
        for i, _ := range args {
            fmt.Println(append(append([]string{}, args[:i]...), args[i+1:]...)) 
        }
    
        fmt.Println(args)
    }
    

    Or, if you want to pass a copy of the slice to a method (and do what you want after that), you can use the copy function…

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集