I’m trying to create a universal function that should compute a slice passed as an argument regardless of its type.
A have a few slices with a different types, but have no idea how to do this properly:
sliceA := []TypeA{}
sliceB := []TypeB{}
func SliceToChunks(arr []any, indices ...int) [][]any {
collection := make([][]any, len(arr))
n1 := indices[0]
...
n6 := indices[5]
collection = append(collection, arr[n1:n2])
collection = append(collection, arr[n3:n4])
collection = append(collection, arr[n5:n6])
return collection
}
chunksA := SliceToChunks(sliceA, 15, 10)
chunksB := SliceToChunks(sliceB, 25, 20)
I will be grateful for your advice.
>Solution :
Not really sure if this is the best method as I don’t fully understand what you’re trying to do, but give this a look.
func SliceToChunks[T any](arr []T, ranges [][2]int) [][]T {
n := len(ranges)
collection := make([][]T, n)
for i := 0; i < n; i++ {
collection[i] = arr[ranges[i][0]:ranges[i][1]]
}
return collection
}
Since you’ve initialized collection with a length (n), you don’t have to use append, you can directly access the index.
Also, loop over the ranges for more concise code.
And finally, use Go’s generics. I don’t encourage using T any, you should union types or use something like comparable, as using any defeats the purpose of having a type system.