Golang bytes. FieldsFunc() function example

package bytes

FieldsFunc interprets the input slice as a sequence of UTF-8-encoded Unicode code points. It splits the slice around each instance of a given rune.

Golang bytes. FieldsFunc() function usage example

 package main

 import (
 "bytes"
 "fmt"
 )

 func main() {

 strslice := []byte("a b c d e f \tg") // \t is tab space

 strfield := bytes.FieldsFunc(strslice, func(divide rune) bool {
 return divide == ' ' // we divide at empty white space
 })

 for i, subslice := range strfield {
 fmt.Printf("Counter %d : %s \n", i, string(subslice))
 }

 utf8slice := []byte("大世界和小世界")

 utf8field := bytes.FieldsFunc(utf8slice, func(divide rune) bool {
 return divide == '和'
 })


 for i, utf8slice := range utf8field {
 fmt.Printf("Counter %d : %s \n", i, string(utf8slice))
 }

 }

Output :

Counter 0 : a

Counter 1 : b

Counter 2 : c

Counter 3 : d

Counter 4 : e

Counter 5 : f

Counter 6 : g

Counter 0 : 大世界

Counter 1 : 小世界

Advertisement