How to test the equivalence of maps in Golang?

前端 未结 8 1328
情歌与酒
情歌与酒 2021-01-30 00:55

I have a table-driven test case like this one:

func CountWords(s string) map[string]int

func TestCountWords(t *testing.T) {
  var tests = []struct {
    input s         


        
8条回答
  •  时光说笑
    2021-01-30 01:12

    The Go library has already got you covered. Do this:

    import "reflect"
    // m1 and m2 are the maps we want to compare
    eq := reflect.DeepEqual(m1, m2)
    if eq {
        fmt.Println("They're equal.")
    } else {
        fmt.Println("They're unequal.")
    }
    

    If you look at the source code for reflect.DeepEqual's Map case, you'll see that it first checks if both maps are nil, then it checks if they have the same length before finally checking to see if they have the same set of (key, value) pairs.

    Because reflect.DeepEqual takes an interface type, it will work on any valid map (map[string]bool, map[struct{}]interface{}, etc). Note that it will also work on non-map values, so be careful that what you're passing to it are really two maps. If you pass it two integers, it will happily tell you whether they are equal.

提交回复
热议问题