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

How to Insert a Value into a Go Slice at a Specific Index Without Affecting Other Elements?

DDD
DDDOriginal
2024-11-19 06:57:03430browse

How to Insert a Value into a Go Slice at a Specific Index Without Affecting Other Elements?

Inserting a Value into a Slice at a Given Index

Question:

How can we insert a value into a specific index in a Go slice without including other elements?

Problem Description:

Suppose we have two slices, array1 and array2, and we want to insert array2[2] at array1[1]. We want to keep the rest of array1 untouched.

Background:

Earlier techniques involved using the colon operator (:), but it also includes subsequent elements. This tutorial aims to provide a comprehensive solution focused on inserting single values at a specific index.

Solution:

Using the slices.Insert Package (Go 1.21 ):

result := slices.Insert(slice, index, value)

Note: 0 ≤ index ≤ len(slice)

Using Append and Assignment

a = append(a[:index+1], a[index:]...)
a[index] = value

Note: len(a) > 0 && index < len(a)

For special cases:

  • If len(a) == index, do:

    a = append(a, value)
  • If inserting at index zero and dealing with an int slice, do:

    a = append([]int{value}, a...)

Custom Function:

func insert(a []int, index int, value int) []int {
    if len(a) == index {
        return append(a, value)
    }
    a = append(a[:index+1], a[index:]...)
    a[index] = value
    return a
}

Generic Function:

func insert[T any](a []T, index int, value T) []T {
    ...
    return a
}

Example:

slice1 := []int{1, 3, 4, 5}
slice2 := []int{2, 4, 6, 8}
slice1 = append(slice1[:2], slice1[1:]...)
slice1[1] = slice2[2]
fmt.Println(slice1) // [1 6 3 4 5]

The above is the detailed content of How to Insert a Value into a Go Slice at a Specific Index Without Affecting Other Elements?. 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