狐狸.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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。