Compare structs

Go structs are compared by value using the `==` operator, but only if all their fields are comparable types.

Go structs are compared by value using the == operator, but only if all their fields are comparable types. If a struct contains a slice, map, or function field, the entire struct becomes uncomparable and will cause a compile-time error if you attempt to compare it directly.

For simple structs with basic types (int, string, bool, etc.), direct comparison works as expected and checks every field for equality. For complex structs containing uncomparable fields, you must manually compare the specific fields you care about or use a helper function.

Here is a direct comparison of two simple structs:

type Point struct {
    X, Y int
}

p1 := Point{1, 2}
p2 := Point{1, 2}
p3 := Point{1, 3}

if p1 == p2 {
    fmt.Println("p1 and p2 are equal")
}
// p1 == p3 returns false

If your struct contains a slice, direct comparison fails:

type User struct {
    Name  string
    Tags  []string // Slice makes the struct uncomparable
}

u1 := User{"Alice", []string{"admin"}}
u2 := User{"Alice", []string{"admin"}}

// This causes a compile error: invalid operation: u1 == u2 (struct containing []string cannot be compared)
// if u1 == u2 { ... }

To compare structs with uncomparable fields, write a custom function that checks the relevant fields individually. For slices, you often need to compare length and elements manually or use reflect.DeepEqual if you need a generic solution (though reflect is slower and should be avoided in hot paths).

func UsersEqual(a, b User) bool {
    if a.Name != b.Name {
        return false
    }
    if len(a.Tags) != len(b.Tags) {
        return false
    }
    for i := range a.Tags {
        if a.Tags[i] != b.Tags[i] {
            return false
        }
    }
    return true
}

// Usage
if UsersEqual(u1, u2) {
    fmt.Println("Users are logically equal")
}

Remember that struct comparison in Go is strict; it does not perform deep comparison on unexported fields if you are writing a custom function, and it requires exact type matches. If you need to compare pointers to structs, == checks if they point to the same memory address, not if the underlying data is identical.