How to delete an element from a Slice in Golang

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

    I take the below approach to remove the item in slice. This helps in readability for others. And also immutable.

    func remove(items []string, item string) []string {
        newitems := []string{}
    
        for _, i := range items {
            if i != item {
                newitems = append(newitems, i)
            }
        }
    
        return newitems
    }
    

提交回复
热议问题