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

Create a slice from another slice but of different type

王林
Release: 2024-02-02 14:13:30
forward
542 people have browsed it

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

}
Copy after login


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
}
Copy after login

and use it:

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template