dongshou2017 2015-03-26 21:27
浏览 85
已采纳

删除切片中的每个元素

I'm getting some unexpected behavior when I try to loop through a slice and remove every element in sequence to print the remaining elements, using the suggested Delete method from SliceTricks. For example, when I try and loop through a slice that contains the letters [A B C], I expect the output to be [B C], [A C], [A B] in that order:

Method 1

package main

import "fmt"

func main() {
    a := []string {"A", "B", "C"}
    for i, _ := range a {
        fmt.Println(append(a[:i], a[i+1:]...))
    }
}

However, the output here is surprising to me. It outputs [B C] three times.

I did eventually get my expected behavior by doing the following:

Method 2

package main

import "fmt"

func main() {
    a := []string {"A", "B", "C"}
    for i, _ := range a {
        result := make([]string, 0)
        result = append(result, a[:i]...)
        result = append(result, a[i+1:]...)
        fmt.Println(result)
    }
}

What is causing the unexpected behavior in method 1 and is there a better way to achieve this other than method 2?

  • 写回答

3条回答 默认 最新

  • dtlrp119999 2015-03-26 23:09
    关注

    The "what" is because append(slice, elems...) is actually updating the slice with the new elements. It returns a "new" slice only because it may have had to relocate the original slice due to memory reallocation. So, in your example code, you are actually changing the contents of a with each call to append. (A good overview is in the "Append: An Example" section of this golang blog post).

    As to "how", my attempt is:

    package main
    
    import "fmt"
    
    func main() {
        a := []string {"A", "B", "C"}
        for i, _ := range a {
            result := make([]string, i, len(a)-1)
            copy(result, a[:i])
            result = append(result, a[i+1:]...)
            fmt.Println(result)
        }
    }
    

    DEMO

    Initializing result with a length and capacity, as well as using copy instead of two appends attempts to reduce the number of memory reallocations required.

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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮