Home >Backend Development >Golang >How to Test Equivalence of Maps in Golang?
Testing Equivalence of Maps in Golang
When writing table-driven tests that involve maps, determining their equivalence can be challenging. One approach is to manually check for equality of lengths and individual key-value pairs, but this becomes repetitive for different map types.
Idiomatic Approach
The Go library offers a built-in solution: reflect.DeepEqual. This function takes two interface{} arguments and recursively compares their values. For maps, it compares lengths, keys, and values using the following steps:
Example Usage
To compare two maps, m1 and m2, use the following code:
import "reflect" eq := reflect.DeepEqual(m1, m2) if eq { fmt.Println("They're equal.") } else { fmt.Println("They're unequal.") }
This solution avoids the need for custom comparison logic and works with various map types. However, note that it will also compare non-map values if passed incorrectly.
The above is the detailed content of How to Test Equivalence of Maps in Golang?. For more information, please follow other related articles on the PHP Chinese website!