How to delete an element from a Slice in Golang

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

    The best way to do it is to use the append function:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        x := []int{4, 5, 6, 7, 88}
        fmt.Println(x)
        x = append(x[:2], x[4:]...)//deletes 6 and 7
        fmt.Println(x)
    }
    

    https://play.golang.org/p/-EEFCsqse4u

提交回复
热议问题