删除元素切片

如果需要从切片中删除一个或多个元素,或者需要使用另一个现有元素的子切片; 你可以使用以下方法。

以下示例使用 slice of int,但适用于所有类型的切片。

所以为此,我们需要一个切片,从巫婆我们将删除一些元素:

slice := []int{1, 2, 3, 4, 5, 6} 
// > [1 2 3 4 5 6]

我们还需要删除元素的索引:

// index of first element to remove (corresponding to the '3' in the slice)
var first = 2

// index of last element to remove (corresponding to the '5' in the slice)
var last = 4 

因此,我们可以切片切片,删除不需要的元素:

// keeping elements from start to 'first element to remove' (not keeping first to remove), 
// removing elements from 'first element to remove' to 'last element to remove'
// and keeping all others elements to the end of the slice
newSlice1 := append(slice[:first], slice[last+1:]...)
// > [1 2 6]

// you can do using directly numbers instead of variables
newSlice2 := append(slice[:2], slice[5:]...)
// > [1 2 6]

// Another way to do the same
newSlice3 := slice[:first + copy(slice[first:], slice[last+1:])]
// > [1 2 6]

// same that newSlice3 with hard coded indexes (without use of variables)
newSlice4 := slice[:2 + copy(slice[2:], slice[5:])]
// > [1 2 6]

要只删除一个元素,只需将此元素的索引作为第一个 AND 作为要删除的最后一个索引,就像这样:

var indexToRemove = 3
newSlice5 := append(slice[:indexToRemove], slice[indexToRemove+1:]...)
// > [1 2 3 5 6]

// hard-coded version:
newSlice5 := append(slice[:3], slice[4:]...)
// > [1 2 3 5 6]

你还可以从切片的开头删除元素:

newSlice6 := append(slice[:0], slice[last+1:]...)
// > [6]

// That can be simplified into
newSlice6 := slice[last+1:]
// > [6]

你还可以从切片的末尾删除一些元素:

newSlice7 := append(slice[:first], slice[first+1:len(slice)-1]...)
// > [1 2]

// That can be simplified into
newSlice7 := slice[:first]
// > [1 2]

如果新切片必须包含与第一个切片完全相同的元素,则可以使用与 last := first-1 相同的内容。
(如果以前计算过索引,这可能很有用)