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
How to add Watermark or Merge two image?
Convert Int data type to Int16 Int32 Int64
How to check pointer or interface is nil?
Regular expression to extract DNS host-name or IP Address from string
Pass different types of arguments in variadic function
How to split a string on white-space?
Find length of Channel, Pointer, Slice, String and Map
Golang HTTP GET request with parameters
How to replace emoji characters in string using regex in Golang?
Get Year, Month, Day, Hour, Min and Second from current date and time.