Home  >  Article  >  Backend Development  >  How to Insert a Value into a Go Slice at a Specific Index?

How to Insert a Value into a Go Slice at a Specific Index?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 01:36:02454browse

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:

  • slices.Insert panics if the index is out of range.
  • The append and insert functions automatically resize the slice if the index is greater than len(slice).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn