How to delete an element from a Slice in Golang

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

    Maybe this code will help.

    It deletes item with a given index.

    Takes the array, and the index to delete and returns a new array pretty much like append function.

    func deleteItem(arr []int, index int) []int{
      if index < 0 || index >= len(arr){
        return []int{-1}
      }
    
        for i := index; i < len(arr) -1; i++{
          arr[i] = arr[i + 1]
    
        }
    
        return arr[:len(arr)-1]
    }
    

    Here you can play with the code : https://play.golang.org/p/aX1Qj40uTVs

提交回复
热议问题