How to Compare Structs in Go

Use the == operator for simple structs or reflect.DeepEqual for structs containing slices, maps, or functions.

Use the == operator to compare two structs of the same type for equality, which checks if all corresponding fields are equal. If the structs contain slices, maps, or functions, use reflect.DeepEqual instead.

package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	X, Y int
}

func main() {
	p1 := Point{1, 2}
	p2 := Point{1, 2}
	fmt.Println(p1 == p2) // true

	s1 := []int{1, 2}
	s2 := []int{1, 2}
	fmt.Println(reflect.DeepEqual(s1, s2)) // true
}