Home >Backend Development >Golang >Create a slice from another slice but of different type
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
.
func f(s []int32) int32 { var newSlice = make([]int64, len(s)) copy(newSlice, s) // how this can be done? // work with newSlice }
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!