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])
}

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


当前回答

找到一条不需要搬迁的路。

更改订单

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]

维持秩序

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]

其他回答

最好的方法是使用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]
}

相同的结果。

我采用下面的方法切片删除项目。这有助于提高其他人的可读性。也是不可变的。

func remove(items []string, item string) []string {
    newitems := []string{}

    for _, i := range items {
        if i != item {
            newitems = append(newitems, i)
        }
    }

    return newitems
}

摘自《Go编程语言》这本书

从切片的中间删除一个元素,保持顺序 对于其余的元素,使用copy来滑动编号较高的元素 减少1来填补空白的元素: 删除(slice []int, I int) []int { 复制(片[我],片[i + 1:]) 返回片(:len(片)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
}

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

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