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
Golang download image from given URL
How to get Dimensions of an image type jpg jpeg png or gif ?
How to import structs from another package in Go?
How to fix race condition using Atomic Functions in Golang?
Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]
How to delete or remove element from a Map?