How to compare equality of struct, slice and map?


DeepEqual function from reflect package used to check x and y are “deeply equal”. This applies for : Array values are deeply equal when their corresponding elements are deeply equal. Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal. Below is a short program to compare struct, slice or map are equal or not.

Example

package main

import (
"fmt"
"reflect"
)

type testStruct struct {
	A int
	B string
	C []int
}

func main() {
	st1 := testStruct{A:100,B:"Australia",C:[]int{1,2,3}}	
	st2 := testStruct{A:100,B:"Australia",C:[]int{1,2,3}}
	fmt.Println("Struct equal: ", reflect.DeepEqual(st1, st2))
	
	
	slice1 := []int{1,2,3,4}
	slice2 := []int{1,2,3,4}
	fmt.Println("Slice equal: ", reflect.DeepEqual(slice1, slice2))
	
	map1 := map[string]int{	
		"x":1,
		"y":2,
	}
	map2 := map[string]int{	
		"x":1,
		"y":2,
		"z":3,
	}
	fmt.Println("Map equal: ",reflect.DeepEqual(map1, map2))
}

Output

Struct equal:  true
Slice equal:  true
Map equal:  false
Most Helpful This Week