Home > Backend Development > Golang > 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
Release: 2024-11-19 01:36:02
Original
526 people have browsed it

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)
Copy after login

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
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template