perhaps? 2014-07-29 21:36 采纳率: 100%
浏览 1481
已采纳

切片中的删除元素

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

  • 写回答

4条回答 默认 最新

  • python小菜 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.

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

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退