Swap Remove For O(1) Unordered Deletion

Delete from the middle of a slice without shifting: overwrite the slot with the last element and truncate, trading order for constant-time removal.

GoResilience

Code

gosnippet
35 lines
package main

import "fmt"

// removeAt 用 swap remove 摘除任务:最后一个元素顶上被删的位置,
// 再截断尾巴。O(1) 完成,但剩余元素顺序不再与入队顺序一致。
func removeAt(jobs []string, i int) []string {
	last := len(jobs) - 1
	jobs[i] = jobs[last]
	return jobs[:last]
}

func indexOf(jobs []string, name string) int {
	for i, job := range jobs {
		if job == name {
			return i
		}
	}
	return -1
}

func main() {
	jobs := []string{"sync-stock", "send-mail", "recalc-score", "push-notify", "index-doc"}

	// 完成顺序与入队顺序无关:按名字定位再摘除,索引不跨轮次复用
	for _, name := range []string{"push-notify", "sync-stock"} {
		i := indexOf(jobs, name)
		if i < 0 {
			panic("missing job: " + name)
		}
		fmt.Println("done:", name)
		jobs = removeAt(jobs, i)
	}
	fmt.Println("remaining:", jobs)
}

The O(1) removal, and what it costs

removeAt(jobs, i) runs two steps: jobs[i] = jobs[last] overwrites the removed slot with the final element, and return jobs[:last] truncates. Nothing shifts, so removal is constant time regardless of position — the price is ordering, stated in the comment: remaining elements no longer match enqueue order.

How the demo’s order gets scrambled

done: push-notify
done: sync-stock
remaining: [index-doc send-mail recalc-score]

Removing "push-notify" at index 3 pulls "index-doc" from the tail into its slot. Removing "sync-stock" at index 0 then pulls the new tail (index-doc again) to the front — which is why the final slice starts with the job that was finished first. indexOf scans by name (return -1 when absent), and a -1 result would abort through panic("missing job: " + name) before any removal.

The line that trades order for speed

jobs[i] = jobs[last]
return jobs[:last]

The comment’s rule — never reuse an index across rounds — is what makes this safe for retry queues: after each swap the positions of surviving jobs are simply unknowable.

Interactive Tools for This Topic

FAQ

What does Swap Remove For O(1) Unordered Deletion print when run?
Invoke the file as-is — the `done:`, `remaining:` prefixes identify which step printed each line.