Go Reference ยท Collections: sort, slices, maps
Go slices.Insert() and slices.Delete() functions
Reference for Go slices.Insert, Delete, DeleteFunc, Replace and Compact: add or remove elements by index, why you must use the result, and zeroed tail elements.
slices.Insert(s, i, vs...) inserts the values vs before index i. slices.Delete(s, i, j) removes the elements s[i:j]. Both return the changed slice, and you must use that result: the old slice variable may point at overwritten or stale data afterwards.
Related functions complete the set: DeleteFunc removes every element that satisfies a predicate, Replace swaps a range for other values, and Compact removes runs of equal elements. They replace the append(s[:i], s[j:]...) idioms that were easy to get wrong.
s := []int{1, 2, 3, 4} s = slices.Delete(s, 1, 3) // [1 4]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Insert[S ~[]E, E any](s S, i int, v ...E) S func Delete[S ~[]E, E any](s S, i, j int) S func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S func Replace[S ~[]E, E any](s S, i, j int, v ...E) S func Compact[S ~[]E, E comparable](s S) S func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S
| Name | Description |
|---|---|
s |
The slice to edit. |
i, j |
Range s[i:j]: i inclusive, j exclusive. For Insert, i is the position to insert before (0 to len(s)). |
v |
Values to insert or to put in place of the range. |
del |
Predicate: elements for which it returns true are removed. |
eq |
Decides whether two neighbors are duplicates in CompactFunc. |
Returns: the edited slice. Its length changes; it may share the array with the input or, for Insert and Replace when capacity is short, be a new array.
Panics: Insert panics if i > len(s). Delete and Replace panic if the range is invalid (i < 0, j > len(s) or i > j).
Usage notes
- Always assign the result.
slices.Delete(s, 1, 2)on its own leavesswith its old length and shifted contents. Writes = slices.Delete(s, 1, 2). - In place, shares memory.
Delete,DeleteFuncandCompactmove elements inside the original array and keep using it. Every other slice that views the same array sees the change. Clone first if you need to keep the original. - The tail is zeroed. Since Go 1.22 the elements beyond the new length are set to their zero value, which lets the garbage collector free pointed-to objects. Code written for Go 1.21 had to clear them by hand.
- Cost:
InsertandDeleteshift the tail, so they areO(n)and not suited to heavy front or middle edits on big slices. For queues use a ring buffer orcontainer/list. DeleteFuncis one pass,O(n), and the right way to filter in place. CallingDeletein a loop isO(nยฒ)and prone to index mistakes.Compactneeds sorted or grouped data to remove all duplicates; sort first withslices.Sort.- Element order is preserved by all of these. If order does not matter, deleting one element by swapping in the last element (
s[i] = s[len(s)-1]; s = s[:len(s)-1]) isO(1).
Related
slices,append,copy,slices.Sort()- Lessons: Slices, Slice internals, The slices and maps packages