如何在切片的开头插入元素?

huangapple go评论96阅读模式
英文:

How to insert element at the beginning of a slice?

问题

我有一个切片:

mySlice := []int{4,5,6,7}
myelement := 3

我想在索引为0的位置插入myelement,使得输出为[3,4,5,6,7]

我该如何做到这一点?

英文:

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?

答案1

得分: 5

你可以在这里使用append属性。

首先,需要使用myelement创建一个切片,然后将该切片附加到mySlice中。

mySlice = append(myelement, mySlice...)

这是一个函数,它将返回将myelement插入到slice的第一个位置后的结果。

func addElementToFirstIndex(x []int, y int) []int {
	x = append([]int{y}, x...)
	return x
}

查看

英文:

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

答案2

得分: 1

func addFirst(s []int, insertValue int) []int {
   res := make([]int, len(s)+1)
   copy(res[1:], s)
   res[0] = insertValue
   return res
}

另一种解决方案,前面的答案更好。

英文:
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.

huangapple
  • 本文由 发表于 2022年2月14日 15:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71108269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定