I have a slice:
mySlice := []int{4,5,6,7}
myelement := 3
I want to insert myelement
at index 0
so that my output will be [3,4,5,6,7]
.
How can I do that?
I have a slice:
mySlice := []int{4,5,6,7}
myelement := 3
I want to insert myelement
at index 0
so that my output will be [3,4,5,6,7]
.
How can I do that?
you can use the append
property here.
first, need to make a slice with the myelement
. then append the slice in mySlice
mySlice = append(myelement, mySlice...)
this is the function that will return the myelement
inserting in the first place of the slice
.
func addElementToFirstIndex(x []int, y int) []int {
x = append([]int{y}, x...)
return x
}
func addFirst(s []int, insertValue int) []int {
res := make([]int, len(s)+1)
copy(res[1:], s)
res[0] = insertValue
return res
}
Another solution, former answers are better.