Split a slice of bytes in Golang

In Go, you can split a slice of bytes into substrings using the bytes.Split() function from the bytes package. This function takes a slice of bytes and a separator as arguments and returns a slice of slices, where each inner slice represents a substring split based on the separator.

Here’s how you can split a slice of bytes:

package main

import (
    "fmt"
    "bytes"
)

func main() {
    // Creating a slice of bytes
    data := []byte("apple,banana,cherry,grape")

    // Splitting the slice using the separator ","
    substrings := bytes.Split(data, []byte(","))

    // Printing the substrings
    for _, substring := range substrings {
        fmt.Println(string(substring))
    }
}

Output :

apple
banana
cherry
grape

In this example, we import the bytes package and create a slice of bytes named data containing comma-separated values. We use bytes.Split() to split the data slice into substrings based on the comma separator.

The function returns a slice of slices, and we iterate through the resulting substrings and print each one using string(substring) to convert the bytes to a string.

Keep in mind that bytes.Split() does not modify the original slice; it creates a new slice containing the split substrings.