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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.