Home  >  Article  >  Backend Development  >  Create a slice from another slice but of different type

Create a slice from another slice but of different type

王林
王林forward
2024-02-02 14:13:30459browse

Create a slice from another slice but of different type

Question content

Is there a simple and readable way to create a copy of a slice but using another type? For example, I received a slice of int32 (mySlice []int32), but I need a copy of it, and the copy should be an int64: copyOfMySlice []int64.

I need something like:

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

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

    // work with newSlice

}

Correct answer


The only way is to translate and copy each element one by one. You can write copy functions using function callbacks:

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
}

and use it:

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

The above is the detailed content of Create a slice from another slice but of different type. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete