SoFunction
Updated on 2025-03-05

Comparison of whether two map[string]interface{} is equal in Go language

Map is disordered in Go

In Go language, Map is a built-in type that binds keys and values ​​together, and can obtain the value of the response through keys.

Since the internal storage mechanism of Go Map is implemented with a key as hash structure, the order is confusing.

For example: The order in which data is read in two traversals is different.

func main() {
    a := map[string]interface{}{
        "orange": "1",
        "apple":  "2",
        "banana": "3",
    }
    ("First time:")
    for k, v := range a {
        (k + " : ")
        (v)
    }
    ("Second time:")
    for k, v := range a {
        (k + " : ")
        (v)
    }
}

Execution results:

First time:
apple : 2
banana : 3
orange : 1
Second time:
banana : 3
orange : 1
apple : 2

Because the maps in Go are unordered, they are different every time they read.

Go interface{} cannot compare whether it is equal

In Go language, two interface{} cannot be compared whether they are equal. Because the type is uncertain, any type of data can be stuffed into the interface{}.

So how do you compare whether two map[string]interface{} are equal?

First, we can convert them into json strings for comparison, but because the map is unordered, the converted json strings may not necessarily be exactly the same. (Of course, you can also use reflection, but the code is too much, it's troublesome.)

So we can convert it into slices in the same order and then convert them to json. This ensures that the json can be the same.

The code is as follows:

func CompareTwoMapInterface(data1 map[string]interface{}, 
                        data2 map[string]interface{}) bool {
    keySlice := make([]string, 0)
    dataSlice1 := make([]interface{}, 0)
    dataSlice2 := make([]interface{}, 0)
    for key, value := range data1 {
        keySlice = append(keySlice, key)
        dataSlice1 = append(dataSlice1, value)
    }
    for _, key := range keySlice {
        if data, ok := data2[key]; ok {
            dataSlice2 = append(dataSlice2, data)
        } else {
            return false
        }
    }
    dataStr1, _ := (dataSlice1)
    dataStr2, _ := (dataSlice2)
    return string(dataStr1) == string(dataStr2)
}

This is the end of this article about comparing whether two map[string]interface{} is equal in Go. For more relevant Go two map[string]interface{} equal content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!