Menu Close

Go – How to split a slice of bytes with separator in go

bytes.Split() function is used to split a slice of bytes with separator in go. It slices a slice of bytes into all sub-slices by separator.

Split() function of bytes package is used to slices s into all sub-slices separated by sep. It returns a slice of the sub-slices between those separators.

Function prototype:

func Split(s, sep []byte) [][]byte

Input parameters:
s: Slice of bytes
sep: byte slice of separator

1: It returns all sub-slices separated by sep of slice s.

Explanation on how to split a slice of bytes with separator in go

  • This Split() function finds separator sep in s, starts from beginning, and convert it into sub-slice. It stores sub-slice into 2D slice array.
  • If sep is empty then Split() function splits after each UTF-8 sequence.


s := []byte("x, y, z")
sep := []byte(",")
bytes.Split(s, sep)

["x" " y" " z"]

s = []byte("x, y, z")
sep = []byte("")
bytes.Split(s, sep)

["x" "," " " "y" "," " " "z"]

s = []byte("x,y,z")
sep = []byte("")
bytes.Split(s, sep)

["x" "," "y" "," "z"]

Example with code:

package main

import (

func main() {

    // Separated by ","
    s := []byte("x, y, z")
    sep := []byte(",")
    fmt.Printf("1) After split: %q", bytes.Split(s, sep))

    // Empty separator
    s = []byte("x, y, z")
    sep = []byte("")
    fmt.Printf("\n2) After split: %q", bytes.Split(s, sep))
    // Having slice s without space and empty separator
    s = []byte("x,y,z")
    sep = []byte("")
    fmt.Printf("\n3) After split: %q", bytes.Split(s, sep))
    // None separator in slice s
    s = []byte("x, y, z")
    sep = []byte("abc")
    fmt.Printf("\n4) After split: %q", bytes.Split(s, sep))
    // Both slice s and separator sep are empty
    s = []byte("")
    sep = []byte("")
    fmt.Printf("\n5) After split: %q", bytes.Split(s, sep))


% go run sample.go

1) After split: ["x" " y" " z"]
2) After split: ["x" "," " " "y" "," " " "z"]
3) After split: ["x" "," "y" "," "z"]
4) After split: ["x, y, z"]
5) After split: []

To learn more about golang, Please refer given below link:


Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published.

Contact Us