Menu Close

Go – bytes.HasSuffix() function in go

bytes.HasSuffix() function is used to check whether byte slice ends with given suffix or not in go.

HasSuffix() built-in function of bytes package or bytes.HasSuffix() function takes two arguments. One argument as byte slice and another argument as suffix byte slice and check whether suffix is present at the end of byte slice or not.

bytes.HasSuffix() function prototype:

func HasSuffix(s, suffix []byte) bool

or

func HasSuffix(s []byte, suffix []byte) bool

Input parameters:
s: byte slice
prefix: byte slice to be used to search as suffix in byte slice s

Return:
It returns true if suffix is present at the end of byte slice s else false.

Explanation:

1)
s := []byte("John is doing well")
prefix := []byte("well")

Output: true, since suffix "well" is present at the end of byte slice "John is doing well".

2)
s := []byte("John is doing well")
prefix := []byte("doing")

Output: false, since suffix "doing" is not present at the end of byte slice "John is doing well" as prefix.

3)
s := []byte{10, 20, 30}
prefix := []byte{10, 20}

Output: true, since prefix {20, 30} is present at the end of byte slice {10, 20, 30}.

4)
s := []byte("去是伟大的!")
prefix := []byte("去是伟大的!")

Output: true, since prefix "去是伟大的!" is present at the end of byte slice "去是伟大的!"

Example:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("John is doing well")
    prefix := []byte("well")

	fmt.Println(bytes.HasSuffix(s, prefix))
	
	
    s = []byte("John is doing well")
    prefix = []byte("doing")
    
    fmt.Println(bytes.HasSuffix(s, prefix))
    
	
    s = []byte{10, 20, 30}
    prefix = []byte{20, 30}

	fmt.Println(bytes.HasSuffix(s, prefix))
	

	s = []byte("去是伟大的!")
    prefix = []byte("去是伟大的!")
	
	fmt.Println(bytes.HasSuffix(s, prefix))
}

Output:

true
false
true
true

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 *