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

Creating fixed length slices from slice

I have a slice of integers which I need to cut into smaller slices and use these new slices to a function call. I have to put 5 objects into every new slice. I could implement a solution which works correctly if the length of the arr1 is dividable with 5. However in other cases I will get an out of range error like this: panic: runtime error: slice bounds out of range [:26] with capacity 24. I understand the problem and its cause, I give wrong index values at the last loop, my logic fails when arr1_len can’t be divided by 5. My question is that how could I slice arr1 into new slices with 5 objects in every slice, except the last one which can hold less than 5.? Playground link

package main

import "fmt"

func printRes(l []int) {
    fmt.Println(l)
}

func sliceTest() {
    arr1 := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}
    arr1_len := len(arr1)
    val := 5
    val2 := 0
    for i := 0; i <= arr1_len; i = i + val {
        val2 = i + val
        currentSlice := arr1[i:val2]
        fmt.Println(i, val2, currentSlice)
        printRes(currentSlice)
    }
}

func main() {
    sliceTest()
}

>Solution :

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

Check bounds:

val2 = i + val
if val2 >= len(arr1) {
    val2 = len(arr1)
}
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