Home »
Golang »
Golang Reference
Golang bytes.FieldsFunc() Function with Examples
Golang | bytes.FieldsFunc() Function: Here, we are going to learn about the FieldsFunc() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021
bytes.FieldsFunc()
The FieldsFunc() function is an inbuilt function of the bytes package which is used to split the given byte slice s at each run of code points c satisfying f(c) and returns a slice of subslices of s. If all code points in s satisfy f(c), or len(s) == 0, an empty slice is returned.
It accepts two parameters (s []byte, f func(rune) bool) and returns a slice of subslices.
Syntax
func FieldsFunc(s []byte, f func(rune) bool) [][]byte
Parameters
- s : The byte slice to be split into a slice of subslices.
- f : The bool function to be checked with each byte of the s.
Return Value
The return type of the bytes.FieldsFunc() function is a [][]byte, it returns a slice of subslices of s.
Example 1
// Golang program to demonstrate the
// example of bytes.FieldsFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
f := func(c rune) bool {
return !unicode.IsLetter(c)
}
fmt.Printf("%q\n", bytes.FieldsFunc(
[]byte("C211, RWA Flats, Delhi65"), f))
fmt.Printf("%q\n", bytes.FieldsFunc(
[]byte("Okay@123!Hello..."), f))
}
Output:
["C" "RWA" "Flats" "Delhi"]
["Okay" "Hello"]
Example 2
// Golang program to demonstrate the
// example of bytes.FieldsFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
f1 := func(c rune) bool {
return !unicode.IsLetter(c)
}
f2 := func(c rune) bool {
return !unicode.IsNumber(c)
}
f3 := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Printf("%q\n", bytes.FieldsFunc(
[]byte("C211, RWA Flats, Delhi65"), f1))
fmt.Printf("%q\n", bytes.FieldsFunc(
[]byte("Okay@123!Hello..."), f2))
fmt.Printf("%q\n", bytes.FieldsFunc(
[]byte("Okay@123!Hello..."), f3))
}
Output:
["C" "RWA" "Flats" "Delhi"]
["123"]
["Okay" "123" "Hello"]
Golang bytes Package »