Golang bytes.FieldsFunc() Function

Golang bytes.FieldsFunc() function is “used to split the input 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.

Syntax

func FieldsFunc(s []byte, f func(rune) bool) [][]byte

Parameters

  1. s: The byte slice is to be split into a slice of subslices.
  2. 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: Splitting a byte slice by vowels

package main

import (
  "bytes"
  "fmt"
)

func isVowel(r rune) bool {
  switch r {
    case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
      return true
    default:
      return false
  }
}

func main() {
  data := []byte("Hello, World!")
  result := bytes.FieldsFunc(data, isVowel)
  fmt.Println(result)
}

Output

[[72] [108 108] [44 32 87] [114 108 100 33]]

Example 2: Splitting a byte slice at numbers

package main

import (
  "bytes"
  "fmt"
  "unicode"
)

func main() {
  data := []byte("abc1def2ghi3jkl")
  result := bytes.FieldsFunc(data, unicode.IsNumber)
  fmt.Println(result)
}

Output

[[97 98 99] [100 101 102] [103 104 105] [106 107 108]]

Example 3: Splitting a byte slice at spaces and punctuation

package main

import (
  "bytes"
  "fmt"
  "unicode"
)

func isSpaceOrPunct(r rune) bool {
 return unicode.IsSpace(r) || unicode.IsPunct(r)
}

func main() {
  data := []byte("Hello, World! How are you?")
  result := bytes.FieldsFunc(data, isSpaceOrPunct)
  fmt.Println(result)
}

Output

[[72 101 108 108 111] [87 111 114 108 100] [72 111 119] [97 114 101] [121 111 117]]

That’s it!

Related posts

Golang bytes.Fields()

Golang bytes.EqualFold()

Golang bytes.Equal()

Golang bytes.CutPrefix()

Golang bytes.Cut()

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Leave a Comment