Golang bytes.Contains() Function

Golang bytes.Contains() function is “used to check whether the given byte subslice is within byte slice.”

Syntax

func Contains(b, subslice []byte) bool

Parameters

  1. b: The byte slice in which we want to check for the presence of the subslice.
  2. subslice: The byte slice we’re looking for in b.

Return value

It returns true if the subslice is found within b and false otherwise.

Example 1: How to Use bytes.Contains() function

package main

import (
  "bytes"
  "fmt"
)

func main() {
  b := []byte("Hello, Golang!")
  sub := []byte("Go")

  if bytes.Contains(b, sub) {
    fmt.Println("b contains sub")
  } else {
    fmt.Println("b does not contain sub")
  }
}

Output

b contains sub

Example 2: Checking the Presence of a Byte Sequence in a File Content

package main

import (
  "bytes"
  "fmt"
  "log"
  "os"
)

func main() {
  fileContent, err := os.ReadFile("new.txt")
  if err != nil {
    log.Fatalf("Error reading the file: %v", err)
  }

  sub := []byte("special_sequence")

  if bytes.Contains(fileContent, sub) {
    fmt.Println("The file contains the special sequence.")
  } else {
    fmt.Println("The file does not contain the special sequence.")
  }
}

Output

The file does not contain the special sequence.

Example 3: Checking for Byte Prefixes

Suppose you want to check if a byte slice starts with a specific prefix.

package main

import (
  "bytes"
  "fmt"
)

func hasPrefix(b, prefix []byte) bool {
  return bytes.Contains(b[:len(prefix)], prefix)
}

func main() {
  b := []byte("Golang is awesome!")
  prefix := []byte("Go")

  if hasPrefix(b, prefix) {
    fmt.Println("The byte slice starts with the prefix.")
  } else {
    fmt.Println("The byte slice does not start with the prefix.")
  }
}

Output

The byte slice starts with the prefix.

In this example, we defined a helper function hasPrefix() that uses bytes.Contains() function to check if a byte slice starts with a given prefix. The main() function then uses this helper function to determine if the byte slice b starts with the prefix “Go”.

That’s it.

Related posts

Go bytes.Clone()

Go bytes.Equal()

Go bytes.Compare()

Leave a Comment