In Golang, reflect.DeepEqual function is used to compare the equality of struct, slice, and map in Golang. It is used to check if two elements are "deeply equal" or not. Deep means that we are comparing the contents of the objects recursively. Two distinct types of values are never deeply equal. Two identical types are deeply equal if one of the following cases is true
1. Slice values are deeply equal when all of the following are true:
C
Output:
C
Output:
- They are both nil or both non-nil.
- Their length is same.
- Either they have same initial entry (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
- They both are nil or non-nil
- Their length is same
- Their corresponding keys have deeply equal values
func DeepEqual(x, y interface{}) bool
Example:
// Golang program to compare equality
// of struct, slice, and map
package main
import (
"fmt"
"reflect"
)
type structeq struct {
X int
Y string
Z []int
}
func main() {
s1 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
s2 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
// comparing struct
if reflect.DeepEqual(s1, s2) {
fmt.Println("Struct is equal")
} else {
fmt.Println("Struct is not equal")
}
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3, 4}
// comparing slice
if reflect.DeepEqual(slice1, slice2) {
fmt.Println("Slice is equal")
} else {
fmt.Println("Slice is not equal")
}
map1 := map[string]int{
"x": 10,
"y": 20,
"z": 30,
}
map2 := map[string]int{
"x": 10,
"y": 20,
"z": 30,
}
// comparing map
if reflect.DeepEqual(map1, map2) {
fmt.Println("Map is equal")
} else {
fmt.Println("Map is not equal")
}
}
Struct is equal Slice is not equal Map is equalHowever, cmp.Equal is a better tool for comparing structs. To use this, we need to import the "github.com/google/go-cmp/cmp" package. Example:
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
type structeq struct {
X int
Y string
Z []int
}
func main() {
s1 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
s2 := structeq{X: 50,
Y: "GeeksforGeeks",
Z: []int{1, 2, 3},
}
// comparing struct
if cmp.Equal(s1, s2) {
fmt.Println("Struct is equal")
} else {
fmt.Println("Struct is not equal")
}
}
Struct is equal