预置所有类型的功能 [英] prepend function for all types in go

查看:96
本文介绍了预置所有类型的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  func prepend(slice [] int,elms ... int)[] int {

newSlice:= [] int {}

for _,elm:=范围elms {
newSlice = append(newSlice,elm )
}

for _,item:=范围片{
newSlice = append(newSlice,item)



return newSlice
}

是否有任何类型的函数是通用的?

这样我就可以放入一片数组了。

另外,有没有更好的方法来编写这个函数?



我还没有在网上找到任何有关写作的资料。 我不认为你可以用类型通用的方式编写这样的函数。但您可以使用 append 来预先设定。

  c = append ([] int {b},a ...)

播放


I have written a very small prepend function for go.

func prepend(slice []int, elms ... int) []int {

   newSlice := []int{}

   for _, elm := range elms {
      newSlice = append(newSlice, elm)
   }

   for _, item := range slice {
      newSlice = append(newSlice, item)

   }

   return newSlice
}

Is there anyway to make the function generic for any type?

So that I can put in a slice of arrays a prepend to that.

Also, is there a better way to write this function?

I have not found anything online about writing one.

解决方案

I don't think you can write such function in a type-generic way. But you can use append to prepend as well.

c = append([]int{b}, a...)

Playground.

这篇关于预置所有类型的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆