Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Compare Structs for Equality in Go

Use == for comparable Go structs, choose reflect.DeepEqual or a custom comparison for slice and map fields, and handle nil versus empty values.

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.

Illustration accompanying struct equality in Go

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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.