Home > Article > Backend Development > How to Insert a Value into a Go Slice at a Specific Index?
Inserting a Value into a Slice at a Given Index
In Go, inserting a value into a slice at a specific index can be done using various methods:
Using the slices.Insert Function (Go 1.21 and Later):
result = slices.Insert(slice, index, value)
Note: index should be between 0 and len(slice).
Using the Append and Assignment Operators:
a = append(a[:index+1], a[index:]...) a[index] = value
Using the insert Function:
func insert(a []int, index int, value int) []int { if index == len(a) { // Nil or empty slice, or after last element return append(a, value) } a = append(a[:index+1], a[index:]...) // Step 1+2 a[index] = value // Step 3 return a }
Benchmarks:
The provided benchmark results indicate that the slices.Insert function is the most efficient for small slice sizes. For larger slices, the append and insert functions perform better.
Handling Index Out of Range:
Generics (Go 1.18 and Later):
func insert[T any](a []T, index int, value T) []T { // Similar to the non-generic function }
The above is the detailed content of How to Insert a Value into a Go Slice at a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!