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

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


当前回答

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

// 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"

其他回答

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

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

也许这段代码会有所帮助。

它删除具有给定索引的项。

接受数组和要删除的索引,并返回一个新数组,类似于append函数。

func deleteItem(arr []int, index int) []int{
  if index < 0 || index >= len(arr){
    return []int{-1}
  }

    for i := index; i < len(arr) -1; i++{
      arr[i] = arr[i + 1]

    }

    return arr[:len(arr)-1]
}

在这里您可以使用代码:https://play.golang.org/p/aX1Qj40uTVs

for index, item := range movies{
    if item.ID == "123"{
        movies = append(movies[:index], movies[index+1:]...)
        break
    }
}

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

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

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

    return newitems
}

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

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

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

因此,正确的解决方案是使用引用到新数组而不是“主”数组的片。 这可以通过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
}

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

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