Compare two arrays/structs in Go

Compare two arrays/structs in Golang

Yash Chauhan
2 min readJan 10, 2023

--

To compare two arrays in Go, you can use the reflect.DeepEqual function from the reflect package. This function will recursively compare the elements of the two arrays and return true if they are equal, and false if they are not.

For example, to compare two arrays of integers, you could do something like this:

package main

import (
"fmt"
"reflect"
)

type LivingObject struct {
eye bool
ears bool
wings bool
}

func main() {
a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
c := [3]int{4, 5, 6}

var Yash LivingObject
Yash.eye = true
Yash.ears = true
Yash.wings = false

var parrot LivingObject
parrot.eye = true
parrot.ears = true
parrot.wings = true

fmt.Println(reflect.DeepEqual(a, b)) // Output: true
fmt.Println(reflect.DeepEqual(a, c)) // Output: false
fmt.Println(reflect.DeepEqual(Yash, parrot)) // Output: false
}

This will output true for the comparison between a and b, since they are both arrays of integers with the same values, and false for the comparison between a and c, since they have different values.

If you want to compare arrays of a different type, such as arrays of structs, you can use the same approach. The DeepEqual function will recursively compare the elements of the arrays, including the fields of the structs.

For example:

type Point struct {
X int
Y int
}

a := [2]Point{{1, 2}, {3, 4}}
b := [2]Point{{1, 2}, {3, 4}}
c := [2]Point{{4, 5}, {6, 7}}

fmt.Println(reflect.DeepEqual(a, b)) // Output: true
fmt.Println(reflect.DeepEqual(a, c)) // Output: false

This will output true for the comparison between a and b, since they are both arrays of Point structs with the same values, and false for the comparison between a and c since they have different values.

Thanks for reading! A few (hopefully 50) claps? are always appreciated. Follow me and share this article if you like it.

--

--

Yash Chauhan
Yash Chauhan

Written by Yash Chauhan

Software Engineer @Qube | Exploring Golang & Reactjs

Responses (1)