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 中国語 Web サイトの他の関連記事を参照してください。