How to delete an element from a Slice in Golang

前端 未结 14 1698
时光取名叫无心
时光取名叫无心 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:18

    No need to check every single element unless you care contents and you can utilize slice append. try it out

    pos := 0
    arr := []int{1, 2, 3, 4, 5, 6, 7, 9}
    fmt.Println("input your position")
    fmt.Scanln(&pos)
    /* you need to check if negative input as well */
    if (pos < len(arr)){
        arr = append(arr[:pos], arr[pos+1:]...)
    } else {
        fmt.Println("position invalid")
    }
    

提交回复
热议问题