How to delete an element from a Slice in Golang

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

    here is the playground example with pointers in it. https://play.golang.org/p/uNpTKeCt0sH

    package main
    
    import (
        "fmt"
    )
    
    type t struct {
        a int
        b string
    }
    
    func (tt *t) String() string{
        return fmt.Sprintf("[%d %s]", tt.a, tt.b)
    }
    
    func remove(slice []*t, i int) []*t {
      copy(slice[i:], slice[i+1:])
      return slice[:len(slice)-1]
    }
    
    func main() {
        a := []*t{&t{1, "a"}, &t{2, "b"}, &t{3, "c"}, &t{4, "d"}, &t{5, "e"}, &t{6, "f"}}
        k := a[3]
        a = remove(a, 3)
        fmt.Printf("%v  ||  %v", a, k)
    }
    

提交回复
热议问题