2

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
  • 2
    `mySlice = append([]int{3}, mySlice...)`. For more see: https://github.com/golang/go/wiki/SliceTricks – mkopriva Feb 14 '22 at 07:15

2 Answers2

6

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
}

See

Emon46
  • 1,506
  • 7
  • 14
1
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.

qloveshmily
  • 1,017
  • 9
  • 5