OneBite.Dev - Coding blog in a bite size

split an array into smaller arrays in Go

Code snippet on how to split an array into smaller arrays in Go

  package main

import "fmt"

func main() {
    mainSlice := []string{"this", "is", "a", "slice", "test"}
    
    //split mainSlice into smaller slices of length = 2
    size := 2
    for i := 0; i < len(mainSlice); i += size {
        end := i + size
        if end > len(mainSlice) {
            end = len(mainSlice)
        }
        fmt.Println(mainSlice[i:end])
    }
}

This code example is written in Go and is used to split an array, called ‘mainSlice’, into smaller arrays. It begins by importing a package, ‘fmt’, which allows the code to use formatted I/O operations such as printing to the console. The main function is then called, which is where the code for splitting the array is written. We then declare the variable ‘size’ and set it to the length of the smaller arrays we want to create. A for loop is then used to loop through mainSlice and create the smaller slices. An ‘end’ variable is also declared and set to our new array length, ‘i + size’. This is used to make sure our slice never goes beyond the length of the mainSlice. Finally, the slice is printed to the console.

go