普通网友 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 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序