Member-only story
Understanding Struct Comparisons and Deep Equality in Go
In Go, two structs can be compared if all their field types are comparable. Comparable types include basic data types (such as integers, floating points, strings, etc.), as well as pointers, arrays, and structs, as long as their elements or field types are also comparable.
Here is an example demonstrating comparable structs:
package main
import "fmt"
type Point struct { X, Y int}
func main() { // Comparable structs point1 := Point{X: 1, Y: 2} point2 := Point{X: 1, Y: 2}
// Use == for comparison if point1 == point2 { fmt.Println("point1 and point2 are equal.") } else { fmt.Println("point1 and point2 are not equal.") }}
In this example, the Point
struct fields X
and Y
are both integer types, which are comparable, so two Point
struct instances can be compared using ==
.
Specifically, if all fields of a struct are of comparable types, then the two structs are comparable, and you can use ==
or !=
for comparison. If a struct contains non-comparable types, such as slices (slice
), maps (map
), or functions, then the struct is not comparable. In such cases, you can use the reflect.DeepEqual
function for a deep comparison.
Extension: Introduction to reflect.DeepEqual
reflect.DeepEqual
is a function in Go's reflect
package used for comparing two values for equality. It can compare various types of values, including basic types, structs…