狐狸.fox 2014-07-29 21:36 采纳率: 0%
浏览 128
已采纳

切片中的删除元素

func main() {
    a := []string{"Hello1", "Hello2", "Hello3"}
    fmt.Println(a)
    // [Hello1 Hello2 Hello3]
    a = append(a[:0], a[1:]...)
    fmt.Println(a)
    // [Hello2 Hello3]
}

How does this delete trick with the append function work?

It would seem that it's grabbing everything before the first element (empty array)

Then appending everything after the first element (position zero)

What does the ... (dot dot dot) do?

转载于:https://stackoverflow.com/questions/25025409/delete-element-in-a-slice

  • 写回答

5条回答 默认 最新

  • Memor.の 2014-07-29 21:47
    关注

    Where a is the slice, and i is the index of the element you want to delete:

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

    ... is syntax for variadic arguments in Go.

    Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println can take as many arguments as you want).

    Now, when calling a function, ... does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.

    So what this line does:

    a = append(a[:0], a[1:]...)
    

    is essentially:

    a = append(a[:0], a[1], a[2])
    

    Now, you may be wondering, why not just do

    a = append(a[1:]...)
    

    Well, the function definition of append is

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

    So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.

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

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算