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

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


当前回答

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

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

其他回答

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

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

从切片包中使用Delete(实验性的,从Go 1.18开始可用):

slice := []int{1, 2, 3, 4}
slice = slices.Delete(slice, 1, 2)
fmt.Println(slice) // [1 3 4]

去游乐场的例子

片。Delete(s, i, j)从s中删除元素s[i:j]

即从索引I到索引j的元素 如果你还记得区间的数学符号:[i,j)

注意两点:

Delete修改原始片的内容 你需要重新分配切片,否则它会有错误的长度

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

也许你可以试试这个方法:

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

用法:

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)

结果:

0, 1, 2, 4, 5
"0", "1", "2", "3", "5"

顺序很重要

如果你想要保持数组的有序,你必须将删除索引右边的所有元素向左移动一个单位。希望在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),依此类推。