从另一个切片创建切片但类型不同

admin 阅读:89 2024-03-14

从另一个切片创建切片但类型不同

问题内容

是否有一种简单易读的方法来创建切片的副本但使用另一种类型? 例如,我收到了 int32 的切片 (mySlice []int32),但我需要它的副本,并且该副本应为 int64: copyOfMySlice []int64

我需要类似的东西:

func f(s []int32) int32 {
    
    var newSlice = make([]int64, len(s))

    copy(newSlice, s) // how this can be done?

    // work with newSlice

}

正确答案


唯一的方法是逐个翻译和复制每个元素。您可以使用函数回调编写复制函数:

func CopySlice[S, T any](source []S, translate func(S) T) []T {
    ret := make([]T, 0, len(source))
    for _, x := range source {
        ret = append(ret, translate(x))
    }
    return ret
}

并使用它:

intSlice:=CopySlice[uint32,int]([]uint32{1,2,3},func(in uint32) int {return int(in)})
声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!