Golang bytes.ContainsAny() Function

Golang bytes.ContainsAny() function is “used to check any of the UTF-8-encoded code points in chars are within bytes.”

Syntax

func ContainsAny(b []byte, chars string) bool

Parameters

  1. b: The main byte slice in which we have to check the chars.
  2. chars: The characters (string) set to be checked within the byte slice b.

Return value

The return type of the bytes.ContainsAny() function is a bool, and it returns true if any character from chars is within the byte slice b; false, otherwise.

Example 1

package main

import (
  "bytes"
  "fmt"
)

func main() {
  // Create a byte slice
  b := []byte("Golang is awesome!")

  // Check if it contains any of the characters in "xyz"
  fmt.Println(bytes.ContainsAny(b, "xyz")) // false

  // Check if it contains any of the characters in "aeiou"
  fmt.Println(bytes.ContainsAny(b, "aeiou")) // true
}

Output

false
true

Example 2

package main

import (
  "bytes"
  "fmt"
)

func main() {
  // Create a byte slice
  b := []byte("你好,世界!")

  // Check if it contains any of the characters in "好大"
  fmt.Println(bytes.ContainsAny(b, "好大"))

  // Check if it contains any of the characters in "abc"
  fmt.Println(bytes.ContainsAny(b, "abc"))
}

Output

true
false

That’s it!

Related posts

Golang bytes.Contains()

Golang bytes.Clone()

Golang bytes.Equal()

Golang bytes.Compare()

Leave a Comment