How to delete an element from a Slice in Golang

前端 未结 14 1565
时光取名叫无心
时光取名叫无心 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条回答
  •  旧时难觅i
    2021-01-30 03:18

    Maybe you can try this method:

    // DelEleInSlice delete an element from slice by index
    //  - arr: the reference of slice
    //  - index: the index of element will be deleted
    func DelEleInSlice(arr interface{}, index int) {
        vField := reflect.ValueOf(arr)
        value := vField.Elem()
        if value.Kind() == reflect.Slice || value.Kind() == reflect.Array {
            result := reflect.AppendSlice(value.Slice(0, index), value.Slice(index+1, value.Len()))
            value.Set(result)
        }
    }
    

    Usage:

    arrInt := []int{0, 1, 2, 3, 4, 5}
    arrStr := []string{"0", "1", "2", "3", "4", "5"}
    DelEleInSlice(&arrInt, 3)
    DelEleInSlice(&arrStr, 4)
    fmt.Println(arrInt)
    fmt.Println(arrStr)
    

    Result:

    0, 1, 2, 4, 5
    "0", "1", "2", "3", "5"
    

提交回复
热议问题