Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert element at the beginning of a slice? [duplicate]

Tags:

slice

go

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?

like image 653
ELIPHOSIF IDHAI Avatar asked Nov 24 '25 20:11

ELIPHOSIF IDHAI


2 Answers

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

like image 96
Emon46 Avatar answered Nov 26 '25 14:11

Emon46


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.

like image 40
qloveshmily Avatar answered Nov 26 '25 13:11

qloveshmily



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!