Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A universal function with a different slice types in argument

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading