在 Go 语言中,可以使用内置的 append()
函数实现数组向指定位置插入值。
语法:
slice =append(slice[:index], append([]T{value}, slice[index:]...)
其中,slice
为要操作的数组,index
为要插入的位置,value
为要插入的值。
例如:
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4, 5}
fmt.Println("original slice:", s)
value := 6
index := 2
s = append(s[:index], append([]int{value}, s[index:]...)
fmt.Println("new slice:", s)
}
输出:
original slice: [1 2 3 4 5]
new slice: [1 2 6 3 4 5]
另外还可以通过切片的方式来实现插入,但是会有性能问题
s = append(s[:index], value)
s = append(s, s[index:]...)
建议使用上面那种方式来实现。