Table of Contents
Use == to compare two Go struct values when their types can be compared and all their fields are comparable. If a struct contains a slice or map, compare those fields explicitly or use reflect.DeepEqual when its rules match what you want.

Use == for comparable structs
Two comparable struct values are equal when their corresponding non-blank fields are equal. The usual case is two values of the same named struct type. Separately named struct types do not become interchangeable just because their fields have the same names.
package main
import "fmt"
type Author struct {
Name string
Books int
}
func main() {
a := Author{Name: "Moana", Books: 3}
b := Author{Name: "Moana", Books: 3}
c := Author{Name: "Dona", Books: 3}
fmt.Println(a == b) // true
fmt.Println(a == c) // false
}
An array field can be comparable if its element type is comparable. A slice, map, or function field prevents direct struct comparison. An interface field can compile in a comparison and still panic if both interface values contain the same uncomparable dynamic type. See the Go comparison rules and the Go arrays guide.
Compare the contents of a slice field
package main
import (
"fmt"
"reflect"
"slices"
)
type Author struct {
Name string
Tags []string
}
func main() {
a := Author{Name: "Moana", Tags: []string{"go"}}
b := Author{Name: "Moana", Tags: []string{"go"}}
fmt.Println(reflect.DeepEqual(a, b)) // true
fmt.Println(a.Name == b.Name && slices.Equal(a.Tags, b.Tags)) // true
}
reflect.DeepEqual distinguishes a nil slice from a non-nil empty slice. slices.Equal, available in the standard library from Go 1.21, treats both as equal. Choose an explicit comparison when you want to ignore fields, treat nil and empty as equivalent, or compare values with application-specific rules.
Reader Comments 0
Sign in with email or Google to join the discussion.