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 {
        new_arr[i] = arr[k]
        k++
        i++
    } else {
        k++
    }
}

for i := 0; i < (len(arr) - 1); i++ {
    fmt.Println(new_arr[i])
}

我正在使用这个命令从切片中删除一个元素,但它不起作用,请建议。


当前回答

最好的方法是使用append函数:

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

其他回答

次要点(代码高尔夫),但在顺序不重要的情况下,你不需要交换值。只需用上一个位置的副本覆盖被删除的数组位置,然后返回一个截断的数组。

func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    return s[:len(s)-1]
}

相同的结果。

顺序很重要

如果你想要保持数组的有序,你必须将删除索引右边的所有元素向左移动一个单位。希望在Golang中可以轻松做到这一点:

func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}

然而,这是低效的,因为您可能最终要移动所有的元素,这是昂贵的。

顺序并不重要

如果你不关心顺序,你可以更快地将要删除的元素替换为片末尾的元素,然后返回第n-1个元素:

func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    return s[:len(s)-1]
}

使用reslicing方法,清空一个包含100万个元素的数组需要224秒,而这个方法只需要0.06ns。

这个答案不执行边界检查。它需要一个有效的索引作为输入。这意味着大于或等于初始len(s)的负值或下标将导致Go panic。

切片和数组是0索引,删除数组的第n个元素意味着提供输入n-1。要删除第一个元素,调用remove(s, 0),要删除第二个元素,调用remove(s, 1),依此类推。

在语言教程中,我们了解到:

片类似于数组的引用。 片不存储任何数据,它只是描述底层数组的一部分。 改变片的元素将修改其底层数组的相应元素。

出于这个原因,在片上使用附加函数而不考虑我们正在处理的值的起源和目的地是非常危险的,也是错误的。

因此,正确的解决方案是使用引用到新数组而不是“主”数组的片。 这可以通过make构造创建一个新切片来实现。

func removeAt(slice []int, index int) []int {
    newSlice := make([]int, 0) //Create a new slice of type []int and length 0
    newSlice = append(newSlice, slice[:index]...) //Copies the values contained in the old slice to the new slice up to the index (excluded)
    if index != len(slice)-1 {
        newSlice = append(newSlice, slice[index+1:]...) //If the index to be removed was different from the last one, then proceed to copy the following values of the index to the end of the old slice
    }
    return newSlice
}

通过这种方式,我们能够安全地删除片中的元素,而不管我们将在函数返回时使用什么。


由于我使用了一个函数来回答这个问题,它将是一个好主意处理任何错误如下:

func removeAt(slice []int, index int) ([]int, error) {
    if index < 0 {
        return nil, fmt.Errorf("index (%d) cannot be a negative number", index)
    }
    if index >= len(slice) {
        return nil, fmt.Errorf("index (%d) cannot be a number greater or equal than the length of slice (%d)", index, len(slice))
    }

    newSlice := make([]int, 0)
    newSlice = append(newSlice, slice[:index]...)
    if index != len(slice)-1 {
        newSlice = append(newSlice, slice[index+1:]...)
    }
    
    return newSlice, nil
}

或者更好的是,实现可以通过接口处理多种类型的函数。 但是,所有这些都是一种很好的实践,因为您构建了一个函数来执行此操作,这与所提出的问题无关。

但是,在这里可以找到一个在围棋操场上测试的例子。

下面是带有指针的操场示例。 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)
}

最好的方法是使用append函数:

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