How to delete an element from a Slice in Golang

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

    Find a way here without relocating.

    • changes order
    a := []string{"A", "B", "C", "D", "E"}
    i := 2
    
    // Remove the element at index i from a.
    a[i] = a[len(a)-1] // Copy last element to index i.
    a[len(a)-1] = ""   // Erase last element (write zero value).
    a = a[:len(a)-1]   // Truncate slice.
    
    fmt.Println(a) // [A B E D]
    
    • keep order
    a := []string{"A", "B", "C", "D", "E"}
    i := 2
    
    // Remove the element at index i from a.
    copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
    a[len(a)-1] = ""     // Erase last element (write zero value).
    a = a[:len(a)-1]     // Truncate slice.
    
    fmt.Println(a) // [A B D E]
    
    0 讨论(0)
  • 2021-01-30 03:15

    From the book The Go Programming Language

    To remove an element from the middle of a slice, preserving the order of the remaining elements, use copy to slide the higher-numbered elements down by one to fill the gap:

    func remove(slice []int, i int) []int {
      copy(slice[i:], slice[i+1:])
      return slice[:len(slice)-1]
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-01-30 03:18

    No need to check every single element unless you care contents and you can utilize slice append. try it out

    pos := 0
    arr := []int{1, 2, 3, 4, 5, 6, 7, 9}
    fmt.Println("input your position")
    fmt.Scanln(&pos)
    /* you need to check if negative input as well */
    if (pos < len(arr)){
        arr = append(arr[:pos], arr[pos+1:]...)
    } else {
        fmt.Println("position invalid")
    }
    
    0 讨论(0)
提交回复
热议问题