Golang bytes.Fields() Function

Golang bytes.Fields() function is “used to split the input byte slice s around each instance of one or more consecutive white space characters and returns a slice of subslices of s or an empty slice if s contains only white space.”

Syntax

func Fields(s []byte) [][]byte

Parameters

s: The byte slice is to be split into a slice of subslices.

Return value

The return type of the bytes.Fields() function is a [][]byte. It returns a slice of subslices of s or an empty slice if s contains only white space.

Example 1: Basic Usage

package main

import (
  "bytes"
  "fmt"
)

func main() {
  data := []byte("Hello World from Go")
  fields := bytes.Fields(data)
  for _, field := range fields {
    fmt.Println(string(field))
  }
}

Output

Hello
World
from
Go

Example 2: Handling Multiple Spaces and Tabs

package main

import (
  "bytes"
  "fmt"
)

func main() {
  data := []byte("Hello World\tfrom\t\tGo")
  fields := bytes.Fields(data)
  for _, field := range fields {
    fmt.Println(string(field))
  }
}

Output

Hello
World
from
Go

Example 3: Empty Input and Only Spaces

package main

import (
  "bytes"
  "fmt"
)

func main() {
  data1 := []byte("")
  data2 := []byte(" ")

  fmt.Println("For empty input:", bytes.Fields(data1))
  fmt.Println("For only spaces:", bytes.Fields(data2))
}

Output

For empty input: []
For only spaces: []

In the third example, since the input either has nothing or only spaces, the bytes.Fields() function returns an empty slice.

That’s all!

Related posts

Golang bytes.EqualFold()

Golang bytes.Equal()

Golang bytes.CutPrefix()

Golang bytes.Cut()

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Golang bytes.Clone()

Leave a Comment