Golang: Check Equality of Unordered Slice Structs

bzon

Bryan Sazon

Posted on March 18, 2021

Golang: Check Equality of Unordered Slice Structs

Playground: https://play.golang.org/p/5GJVPn3X8k7

package main

import (
    "fmt"
    "reflect"
)

type person struct {
    name string
    age  int
}

func main() {
    // Two equal slices but order is different
    aa := []person{{"foo", 1}, {"bar", 2}}
    bb := []person{{"bar", 2}, {"foo", 1}}
    fmt.Println(reflect.DeepEqual(aa, bb))
    fmt.Println(isEqual(aa, bb))
}

// Check and ensure that all elements exists in another slice and
// check if the length of the slices are equal.
func isEqual(aa, bb []person) bool {
    eqCtr := 0
    for _, a := range aa {
        for _, b := range bb {
            if reflect.DeepEqual(a, b) {
                eqCtr++
            }
        }
    }
    if eqCtr != len(bb) || len(aa) != len(bb) {
        return false
    }
    return true
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bzon
Bryan Sazon

Posted on March 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related