How to delete an element from a Slice in Golang

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

    Minor point (code golf), but in the case where order does not matter you don't need to swap the values. Just overwrite the array position being removed with a duplicate of the last position and then return a truncated array.

    func remove(s []int, i int) []int {
        s[i] = s[len(s)-1]
        return s[:len(s)-1]
    }
    

    Same result.

提交回复
热议问题