×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang bytes.HasPrefix() Function with Examples

Golang | bytes.HasPrefix() Function: Here, we are going to learn about the HasPrefix() function of the bytes package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 23, 2021

bytes.HasPrefix()

The HasPrefix() function is an inbuilt function of the bytes package which is used to check whether the byte slice s begins with prefix.

It accepts two parameters (s, prefix []byte) and returns true if the byte slice begins with prefix; false, otherwise.

Syntax

func HasPrefix(s, prefix []byte) bool

Parameters

  • s : The byte slice to be checked whether it is started with prefix or not.
  • prefix : The byte slice to be checked.

Return Value

The return type of the bytes.HasPrefix() function is a bool, it returns true if the byte slice begins with prefix; false, otherwise.

Example 1

// Golang program to demonstrate the
// example of bytes.HasPrefix() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.HasPrefix(
		[]byte("Hi! How are you"), []byte("Hi!")))
	fmt.Println(bytes.HasPrefix(
		[]byte("Hi! How are you"), []byte("Hi")))
	fmt.Println(bytes.HasPrefix(
		[]byte("Hi! How are you"), []byte("Hello")))
}

Output:

true
true
false

Example 2

// Golang program to demonstrate the
// example of bytes.HasPrefix() function

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var str string
	var prefix string

	str = "Hi there!"
	prefix = "Hi"

	if bytes.HasPrefix([]byte(str), []byte(prefix)) == true {
		fmt.Printf("Yes, %q is started with %q\n", str, prefix)
	} else {
		fmt.Printf("No, %q is not started with %q\n", str, prefix)
	}

	str = "Aspire to inspire before we expire."
	prefix = "Asp"

	if bytes.HasPrefix([]byte(str), []byte(prefix)) == true {
		fmt.Printf("Yes, %q is started with %q\n", str, prefix)
	} else {
		fmt.Printf("No, %q is not started with %q\n", str, prefix)
	}

	str = "Aspire to inspire before we expire."
	prefix = "H"

	if bytes.HasPrefix([]byte(str), []byte(prefix)) == true {
		fmt.Printf("Yes, %q is started with %q\n", str, prefix)
	} else {
		fmt.Printf("No, %q is not started with %q\n", str, prefix)
	}
}

Output:

Yes, "Hi there!" is started with "Hi"
Yes, "Aspire to inspire before we expire." is started with "Asp"
No, "Aspire to inspire before we expire." is not started with "H"

Golang bytes Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.