首頁 > 後端開發 > Golang > 如何將值插入給定索引處的 Go 切片中?

如何將值插入給定索引處的 Go 切片中?

Patricia Arquette
發布: 2024-11-15 08:50:02
原創
721 人瀏覽過

How do you insert values into a Go slice at a given index?

Insert Values into a Slice at a Given Index

In Go, inserting values into a slice at a specific index requires careful consideration of the slice's length, capacity, and whether the index falls within its bounds.

Inserting at an Available Index

If the index you want to insert at is within the range of the slice's existing elements, you can use the following approach:

slice1 := []int{1, 3, 4, 5}
slice1 = append(slice1[:index+1], slice1[index:]...)
slice1[index] = value
登入後複製

This approach:

  1. Creates a new slice composed of the elements before and after the insertion point (excluding the element at the insertion point).
  2. Inserts the new value at the desired index.

Inserting at a New Index

If the index you want to insert at is greater than the current length of the slice, you need to expand the slice's capacity to accommodate the new element.

index := 7
if index > cap(slice1) {
    newCap := cap(slice1) * 2 // Double the capacity
    slice1 = append(make([]int, len(slice1), newCap), slice1...)
}
slice1 = append(slice1[:index+1], slice1[index:]...)
slice1[index] = value
登入後複製

This approach:

  1. Checks if the index is beyond the slice's capacity and, if necessary, creates a new slice with double the capacity.
  2. Inserts the new value at the desired index.

Inserting at the End of the Slice

To insert at the end of the slice, you can simply append the new value:

slice1 := []int{1, 3, 4, 5}
slice1 = append(slice1, value)
登入後複製

Using the 'slices' Package (for Go 1.21+)

For Go version 1.21 and above, you can use the slices.Insert() function from the github.com/golang/exp/slices package:

import "github.com/golang/exp/slices"

slice1 := []int{1, 3, 4, 5}
slices.Insert(slice1, index, value)
登入後複製

Example:

array1 := []int{1, 3, 4, 5}
array2 := []int{2, 4, 6, 8}

index := 1 // Index to insert at
value := array2[2] // Value to insert

// Insert value into array1 at index
slice1 := array1[:index+1]
slice2 := array1[index:]
slice1 = append(slice1, value)
slice1 = append(slice1, slice2...)
array1 = slice1

// Result: [1, 6, 3, 4, 5]
登入後複製

以上是如何將值插入給定索引處的 Go 切片中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板