dongyinting3179 2014-07-29 21:36
浏览 66
已采纳

删除切片中的元素

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?

  • 写回答

6条回答 默认 最新

  • doujiu5464 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.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?