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:
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:
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中文網其他相關文章!