Menu Close

Go – Trim suffix bytes in slice of bytes in go

Here, bytes.TrimSuffix() function is used to trim suffix bytes in slice of bytes in go. It trims trailing suffix in slice of bytes.

TrimSuffix() built-in function of bytes package returns slice of bytes without the provided trailing suffix  string.

bytes.TrimSuffix() function prototype:

func TrimSuffix(s, suffix []byte) []byte

Input parameters:
s: slice of bytes
prefix: Slice of bytes to be trimmed trailing suffix  in s

Return:
It returns slice of bytes without the provided trailing suffix string.

Explanation on trim suffix bytes in slice of bytes in go

1)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("baz")

Output:
"foo bar 123 4  "

2)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("bar")

Output:
"foo bar 123 4  baz"

3)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("")

Output:
"foo bar 123 4  baz"

4)
s := []byte("foo bar 123 4  baz")
prefix := []bytes("John")

Output:
"foo bar 123 4  baz"

Example:

Code 1:

package main

import (
    "fmt"
    "bytes"
)


func main() {
    s := []byte("foo bar 123 4  baz")
    prefix := []byte("baz")
    
    fmt.Printf("%q", bytes.TrimSuffix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("bar")
    
    fmt.Printf("\n%q", bytes.TrimSuffix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("")
    
    fmt.Printf("\n%q", bytes.TrimSuffix(s, prefix))
    
    
    s = []byte("foo bar 123 4  baz")
    prefix = []byte("John")
    
    fmt.Printf("\n%q", bytes.TrimSuffix(s, prefix))
}

Output:

% go run sample.go

"foo bar 123 4  "
"foo bar 123 4  baz"
"foo bar 123 4  baz"
"foo bar 123 4  baz"

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *