How to delete an element from a Slice in Golang

前端 未结 14 1450
时光取名叫无心
时光取名叫无心 2021-01-30 03:03
fmt.Println(\"Enter position to delete::\")
fmt.Scanln(&pos)

new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
    if i != pos {
           


        
14条回答
  •  悲&欢浪女
    2021-01-30 03:33

    This is how you Delete From a slice the idiomatic way. You don't need to build a function it is built into the append. Try it here https://play.golang.org/p/QMXn9-6gU5P

    z := []int{9, 8, 7, 6, 5, 3, 2, 1, 0}
    fmt.Println(z)  //will print Answer [9 8 7 6 5 3 2 1 0]
    
    z = append(z[:2], z[4:]...)
    fmt.Println(z)   //will print Answer [9 8 5 3 2 1 0]
    

提交回复
热议问题