Menu Close

Go – bytes.HasPrefix() function in go

bytes.HasPrefix() function is used to check whether given prefix is present in byte slice or not in go.

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

bytes.HasPrefix() function prototype:

func HasPrefix(s, prefix []byte) bool

or

func HasPrefix(s []byte, prefix []byte) bool

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

Return:
It returns true if prefix is present in byte slice s else false.

Explanation:

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

Output: true, since prefix "Jhon" is present at beginning of byte slice "John is doing well".

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

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

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

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

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

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

Example:

package main

import (
	"bytes"
	"fmt"
)

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

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

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

	s = []byte("去是伟大的!")
    prefix = []byte("去是伟大的!")
	
	fmt.Println(bytes.HasPrefix(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 *