Home »
Golang »
Golang Reference
Golang bytes.TrimRightFunc() Function with Examples
Golang | bytes.TrimRightFunc() Function: Here, we are going to learn about the TrimRightFunc() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 29, 2021
bytes.TrimRightFunc()
The TrimRightFunc() function is an inbuilt function of the bytes package which is used to get a subslice of the byte slice (s) by slicing off all trailing UTF-8-encoded code points c that satisfy f(c).
It accepts two parameters (s []byte, f func(r rune) bool) and returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in the cutset.
Syntax
func TrimRightFunc(s []byte, f func(r rune) bool) []byte
Parameters
- s : The byte slice for trimming.
- f : The bool function to check and remove the trailing bytes.
Return Value
The return type of the TrimRightFunc() function is a []byte, it returns a subslice of s by slicing off all trailing UTF-8-encoded code points that are contained in the cutset.
Example 1
// Golang program to demonstrate the
// example of bytes.TrimRightFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
// Returns true if character is either letter or number
// Thus, the bytes.TrimRightFunc() function will remove all
// trailing letters or numbers
f := func(c rune) bool {
return unicode.IsLetter(c) || unicode.IsNumber(c)
}
fmt.Printf("%q\n", bytes.TrimRightFunc(
[]byte("C211, RWA Flats, Delhi65"), f))
fmt.Printf("%q\n", bytes.TrimRightFunc(
[]byte("Okay@123!Hello...End"), f))
}
Output:
"C211, RWA Flats, "
"Okay@123!Hello..."
Example 2
// Golang program to demonstrate the
// example of bytes.TrimRightFunc() function
package main
import (
"bytes"
"fmt"
"unicode"
)
func main() {
// Returns true if character is letter
f1 := func(c rune) bool {
return unicode.IsLetter(c)
}
// Returns true if character is number
f2 := func(c rune) bool {
return unicode.IsNumber(c)
}
// Returns true if character is either letter or number
f3 := func(c rune) bool {
return unicode.IsLetter(c) || unicode.IsNumber(c)
}
fmt.Printf("%q\n", bytes.TrimRightFunc(
[]byte("abcd123abcd"), f1))
fmt.Printf("%q\n", bytes.TrimRightFunc(
[]byte("123abcd456"), f2))
fmt.Printf("%q\n", bytes.TrimRightFunc(
[]byte("abc123@IncludeHelp#456xyz"), f3))
}
Output:
"abcd123"
"123abcd"
"abc123@IncludeHelp#"
Golang bytes Package »