Go - Insert values into a slice

发布时间 2023-10-07 22:54:57作者: ZhangZhihuiAAA

There is no built - in function for insertion, but you can still use append for the task. Let’s say you want to insert the number 1000 between elements at index 2 and 3, which are ints 159 and 26, respectively:

numbers   :=   [] int { 3 ,   14 ,   159 ,   26 ,   53 ,   58 } 
numbers   =   append ( numbers [: 2 + 1 ],   numbers [ 2 :] ... ) 
numbers [ 3 ]   =   1000

 

What if you want to add an element to the beginning of the slice; for example, you want to add the integer 2000 to the beginning of the slice.

numbers   =   append ([] int { 2000 },   numbers ... )

 

What if you want to add a slice of numbers in between two elements of another slice of numbers? For example, you want to insert the slice []int{1000, 2000, 3000, 4000} in between index 2 and 3 of the numbers slice like before.

There are a few ways of doing this, but stick with using append , which is one of the shortest ways:

numbers   =   [] int { 3 ,   14 ,   159 ,   26 ,   53 ,   58 } 
inserted   :=   [] int { 1000 ,   2000 ,   3000 ,   4000 } 

tail   :=   append ([] int {},   numbers [ 3 :] ... ) 
numbers   =   append ( numbers [: 3 ],   inserted ... ) 
numbers   =   append ( numbers ,   tail ... )

First of all, you need to create another slice, tail , to store the tail part of the original slice. You can’t simply slice it and store it into another variable (this is called shallow copy ), because slices are not arrays: they are a pointer to a part of the array and its length. If you slice numbers and store it in tail , when you change numbers , tail will also change, and that is not what you want. Instead, you want to create a new slice by appending it to an empty slice of ints.