3 回答

TA貢獻1856條經驗 獲得超11個贊
從Slice Tricks頁面引用刪除 index 處的元素i:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
請注意,如果您計劃從當前循環的切片中刪除元素,則可能會導致問題。如果您刪除的元素是當前元素(或已循環的前一個元素),則它會這樣做,因為刪除后所有后續元素都被移位,但range循環不知道這一點,并且仍會增加索引并且您跳過一個元素.
您可以通過使用向下循環來避免這種情況:
for i := len(config.Applications) - 1; i >= 0; i-- {
application := config.Applications[i]
// Condition to decide if current element has to be deleted:
if haveToDelete {
config.Applications = append(config.Applications[:i],
config.Applications[i+1:]...)
}
}

TA貢獻1895條經驗 獲得超7個贊
您收到此錯誤是因為您正在對初始范圍為 X 長度的切片進行循環,該范圍變為 Xn,因為您在循環期間刪除了一些元素。
如果要從切片中刪除特定索引處的項目,可以這樣做:
sliceA = append(sliceA[:indexOfElementToRemove], sliceA[indexOfElementToRemove+1:]...)

TA貢獻1757條經驗 獲得超8個贊
這個問題有點老了,但我還沒有在 StackOverflow 上找到另一個答案,其中提到了Slice Tricks 中用于過濾列表的以下技巧:
b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
}
因此,在這種情況下,刪除某些元素的函數可能如下所示:
func removeApplications(apps []Applications) []Applications {
filteredApps := apps[:0]
for _, app := apps {
if !removeApp {
filteredApps = append(filteredApps, app)
}
}
return filteredApps
}
- 3 回答
- 0 關注
- 1958 瀏覽
添加回答
舉報