Skip to content

Compare if Slices Are Equal in Golang (Struct, Map, Interface, …)

The simplest way to check if two structs are equal is using the DeepEqual method from the reflect package:

func DeepEqual(x, y interface{}) bool

See this example which shows the order of the slice is important in comparison:

package main

import (
	"fmt"
	"reflect"
)

type UserIDs struct {
	IDs []int
}

func main() {

	mortezaIDs := UserIDs{
		IDs: []int{1, 2, 3},
	}

	jackIDs := UserIDs{
		IDs: []int{1, 3, 2},
	}

	areEqual := reflect.DeepEqual(mortezaIDs, jackIDs)

	fmt.Println(areEqual)
}

Leave a Reply

Your email address will not be published. Required fields are marked *