Golang bytes.EqualFold() Function

Golang bytes.EqualFold() function is used to check whether the given byte slices s and t (interpreted as UTF-8 strings) are equal under Unicode case-folding, a more general form of case-insensitivity.

Syntax

func EqualFold(s, t []byte) bool

Parameters

s, t: The byte slices to be checked.

Return value

The return type of the bytes.EqualFold() function is a boolean, and it returns true if b and t are equal under Unicode case-folding; false otherwise.

Example 1: Basic Comparison

package main

import (
  "bytes"
  "fmt"
)

func main() {
  a := []byte("Hello")
  b := []byte("HELLO")

  if bytes.EqualFold(a, b) {
    fmt.Println("The slices are equal (case-insensitive).")
  } else {
    fmt.Println("The slices are not equal.")
 }
}

Output

The slices are equal (case-insensitive).

Example 2: Comparing User Input

This example compares user input against a predefined value.

package main

import (
  "bytes"
  "fmt"
)

func main() {
  userInput := []byte("EnterPasswordHere")
  correctPassword := []byte("ENTERpasswordHERE")

  if bytes.EqualFold(userInput, correctPassword) {
    fmt.Println("Access granted.")
  } else {
    fmt.Println("Access denied.")
  }
}

Output

Access granted.

Example 3: Comparing in a Loop

package main

import (
  "bytes"
  "fmt"
)

func main() {
  list1 := [][]byte{
    []byte("apple"),
    []byte("banana"),
    []byte("cherry"),
  }

  list2 := [][]byte{
    []byte("APPLE"),
    []byte("BAnAna"),
    []byte("chERRY"),
  }

  for i, item := range list1 {
    if bytes.EqualFold(item, list2[i]) {
      fmt.Printf("Item %d in both lists are equal (case-insensitive).\n", i+1)
    } else {
      fmt.Printf("Item %d in the lists are not equal.\n", i+1)
    }
  }
}

Output

Item 1 in both lists are equal (case-insensitive).
Item 2 in both lists are equal (case-insensitive).
Item 3 in both lists are equal (case-insensitive).

That’s it!

Related posts

Golang bytes.Equal()

Golang bytes.CutPrefix()

Golang bytes.Cut()

Golang bytes.ContainsRune()

Golang bytes.ContainsFunc()

Golang bytes.ContainsAny()

Golang bytes.Contains()

Golang bytes.Clone()

Leave a Comment