dsjbest2014 2018-01-21 17:14
浏览 49
已采纳

尝试使用append删除字符串数组中的连续项

I have trouble understanding the following result. I am expecting the code

package main
import "fmt"

func main() {
    fruits := []string{"apple", "banana", "orange", "kiwi", "ananas"}
    for i, _ := range fruits {
        s := append(fruits[:i], fruits[i+1:]...)
        fmt.Println(s)
    }
}

to return :

[banana orange kiwi ananas]
[apple orange kiwi ananas]
[apple banana kiwi ananas]
[apple banana orange ananas]
[apple banana orange kiwi]

instead it returns :

[banana orange kiwi ananas]
[banana kiwi ananas ananas]
[banana kiwi ananas ananas]
[banana kiwi ananas ananas]
[banana kiwi ananas ananas]

what am i missing? Note: I am note looking for code that returns the expected behavior, just trying to understand what the code does. Playground : https://play.golang.org/p/CB73GYvY7aW

  • 写回答

1条回答 默认 最新

  • doormen2014 2018-01-21 17:34
    关注

    As the spec say:

    The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.

    In your case, the underlying slice is always sufficient, so it modifies it every time. The result is expectable according to the spec.

    The s/fruit of each loop:

    [banana orange kiwi ananas] [banana orange kiwi ananas ananas]
    [banana kiwi ananas ananas] [banana kiwi ananas ananas ananas]
    [banana kiwi ananas ananas] [banana kiwi ananas ananas ananas]
    [banana kiwi ananas ananas] [banana kiwi ananas ananas ananas]
    [banana kiwi ananas ananas] [banana kiwi ananas ananas ananas]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 VUE项目怎么运行,系统打不开