How to delete an element from a Slice in Golang

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

    Remove one element from the Slice (this is called 're-slicing'):

    package main
    
    import (
        "fmt"
    )
    
    func RemoveIndex(s []int, index int) []int {
        return append(s[:index], s[index+1:]...)
    }
    
    func main() {
        all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
        fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
        all = RemoveIndex(all, 5)
        fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
    }
    

提交回复
热议问题