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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度