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

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


当前回答

使用泛型,您可以传递任何类型的片。

// Removes slice element at index(s) and returns new slice
func remove[T any](slice []T, s int) []T {
    return append(slice[:s], slice[s+1:]...)
}

使用

slice := []int{1, 2, 3, 4}
result := remove(slice, 0)
fmt.Println(result)
// [2 3 4]

例子 https://go.dev/play/p/LhPGvEuZbRA

其他回答

从切片中移除一个元素(这称为“重新切片”):

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

T. Claverie目前投票最多的答案是正确的,但我发现如果只在需要时执行交换,即对片的最后一个元素以外的所有元素执行交换,算法会更清晰。这可以通过一个简单的if守卫来实现。

秩序不重要/没有进行边界检查

func remove(s []int, i int) []int {
    // bring element to remove at the end if its not there yet
    if i != len(s)-1 {
        s[i] = s[len(s)-1]
    }
 
    // drop the last element
    return s[:len(s)-1]
}
for index, item := range movies{
    if item.ID == "123"{
        movies = append(movies[:index], movies[index+1:]...)
        break
    }
}

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

没有必要检查每一个元素,除非你关心的内容,你可以利用切片追加。试试吧

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