douxin8383 2017-07-20 02:51
浏览 31
已采纳

以下Go数组操作起什么作用?

I am confused about how the following code works, especially what is the purpose of "..."

array = append(array[:i], array[i+1:]...)
  • 写回答

4条回答 默认 最新

  • doupang3062 2017-07-20 07:32
    关注

    The line

    a = append(a[:i], a[i+1:]...)
    

    creates a new slice by removing the item at position i in a, by combining the items from 0 to i (not included), and from i+1 to the end.

    Your second question is what is the purpose of .... append accepts a slice as first argument, and an unlimited number of arguments, all with a type assignable to the type of its elements.

    append is defined as

    func append(slice []Type, elems ...Type) []Type
    

    Writing

    a = append(a[:i], a[i+1:]...)
    

    is equivalent as writing

    a = append(a[:i], a[i+1], a[i+2], a[i+3], a[i+4]) //and so on, until the end of the slice.
    

    Using a[i+1:]... is basically a shorthand syntax, as the Go spec describes in https://golang.org/ref/spec#Passing_arguments_to_..._parameters:

    If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T

    Playground

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

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码