To split a byte slice into lines and iterate over them using the bytes package in Go, you can utilize the bytes.Split()
function to split the input byte slice into individual lines based on a delimiter. Here's an example code snippet that demonstrates this:
package main
import (
"bytes"
"fmt"
)
func main() {
input := []byte("line1\nline2\nline3\n")
// Split the input byte slice into lines using the newline delimiter
lines := bytes.Split(input, []byte("\n"))
// Iterate over the lines and print them
for _, line := range lines {
fmt.Println(string(line))
}
}
In this example, we have a byte slice named input
that contains multiple lines separated by newline characters (\n
). We use the bytes.Split()
function to split the input byte slice into lines by specifying the delimiter as []byte("\n")
. This returns a slice of byte slices, where each element represents a line.
We then iterate over the lines using a for
loop and convert each line to a string using string(line)
to print it. This will output:
line1
line2
line3
Note that the trailing newline after the last line is considered as a separate line in this case. If you want to exclude empty lines or handle different line delimiters, you can modify the code accordingly by adjusting the delimiter or adding additional conditions.