Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to check for structure equality in Golang Structures

Anjana Shankar

What is a struct in Go?

A struct or structure in Go is a user-defined type. It helps with composing different types into a single unit.

type Employee struct {
  firstName string
  secondName string
  id int
}

When can you compare two structures?

In order to compare two structures, it is imperative that all struct field types are comparable. If the variables being compared belong to different structures, then you will see a compilation error. Golang allows you to compare two structures if they are of the same type and contain the same values for all fields.

Two ways to check for structure equality

  1. == operator
  2. DeepEqual()

Let’s use the structure defined above and see the two methods in action.

package main
import (
  "fmt"
  "reflect"
)

type Employee struct {
  firstName string
  secondName string
  id  int
}

func main() {
    e1 := Employee {
      firstName: "Anjana",
      secondName: "Shankar",
      id: 1,
    }

    e2 := Employee {
      firstName: "Anjana",
      secondName: "Shankar",
      id: 1,
    }

    e3 := Employee {
      firstName: "Anjana",
      secondName: "Shan",
      id: 1,
    }

    fmt.Println("== Operator in practice")

    if e1 == e2 {
      fmt.Println("e1 == e2")
    } else {
      fmt.Println("e1 != e2")
    }

    if e2 == e3 {
      fmt.Println("e2 == e3")
    } else {
      fmt.Println("e2 != e3")
    }

    fmt.Println("DeepEqual() in practice")

    fmt.Println("Is e1 equal to e2 : ", reflect.DeepEqual(e1, e2))

    fmt.Println("Is e2 equal to e3 : ", reflect.DeepEqual(e2, e3))
}

The == operator does a strict comparison, whereas the reflect.DeepEqual method can help you compare the content of the element your pointers point to.

package main
import (
  "fmt"
  "reflect"
)

type Employee struct {
  firstName string
  secondName string
  id  *int
}

func main() {
    id1 := 1
    id2 := 1
    id3 := 1
    e1 := Employee {
      firstName: "Anjana",
      secondName: "Shankar",
      id: &id1,
    }

    e2 := Employee {
      firstName: "Anjana",
      secondName: "Shankar",
      id: &id2,
    }

    e3 := Employee {
      firstName: "Anjana",
      secondName: "Shan",
      id: &id3,
    }

    fmt.Println("== Operator in practice")

    if e1 == e2 {
      fmt.Println("e1 == e2")
    } else {
      fmt.Println("e1 != e2")
    }

    if e2 == e3 {
      fmt.Println("e2 == e3")
    } else {
      fmt.Println("e2 != e3")
    }

    fmt.Println("DeepEqual() in practice")

    fmt.Println("Is e1 equal to e2 : ", reflect.DeepEqual(e1, e2))

    fmt.Println("Is e2 equal to e3 : ", reflect.DeepEqual(e2, e3))
}

RELATED TAGS

golang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring