What is reflect.DeepEqual() Function in Golang

Golang reflect.DeepEqual() function is “used to check whether x and y are deeply equal.” Deep equality means that not only the top-level values are compared, but also their elements or fields, recursively.

Syntax

func DeepEqual(x, y interface{}) bool

Parameters

The function accepts two arguments, x, and y, of type interface{}. This means you can pass any value to the function, and it will attempt to compare them.

Return value

It returns a boolean value, suggesting the two values are deeply equal.

Example 1

package main

import (
  "fmt"
  "reflect"
)

type Person struct {
  Name string
  Age int
  Hobby []string
}

func main() {
  p1 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

  p2 := Person{
    Name: "Krunal",
    Age: 30,
    Hobby: []string{"investing", "dancing"},
 }

 if reflect.DeepEqual(p1, p2) {
   fmt.Println("p1 and p2 are deeply equal")
 } else {
   fmt.Println("p1 and p2 are not deeply equal")
 }
}

Output

p1 and p2 are not deeply equal

Example 2

package main

import (
  "fmt"
  "reflect"
)

type Person struct {
  Name string
  Age int
  Hobby []string
}

func main() {
  p1 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

  p2 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

 if reflect.DeepEqual(p1, p2) {
   fmt.Println("p1 and p2 are deeply equal")
 } else {
   fmt.Println("p1 and p2 are not deeply equal")
 }
}

Output

p1 and p2 are deeply equal

That’s it.

Related posts

Go reflect.TypeOf()

Leave a Comment