Golang bytes.LastIndexFunc() function example

package bytes

LastIndexFunc interprets given input as a sequence of UTF-8-encoded Unicode code points. It returns the byte index of the last occurrence of the search key in the given input of the first Unicode code point satisfying the search and return -1 if there is no match.

Golang bytes.LastIndexFunc() function usage example

 package main

 import (
 "bytes"
 "fmt"
 )

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

 utf8byteindex := bytes.LastIndexFunc(utf8slice, func(searchkey rune) bool {
 return searchkey == '和'
 })

 fmt.Printf("和 last index num is %d inside the string %s\n",  utf8byteindex, string(utf8slice))

 // now see the diff

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

 utf8byteindex2 := bytes.LastIndexFunc(utf8slice2, func(searchkey rune) bool {
 return searchkey == '和'
 })

 fmt.Printf("和 last index num is %d inside the string %s\n",  utf8byteindex2, string(utf8slice2))

 }

Output :

和 last index num is 9 inside the string 大世界和小世界

和 last index num is 22 inside the string 大世界和小世界 和 <--- take the last index of 和

Reference :

http://golang.org/pkg/bytes/#LastIndexFunc

Advertisement