How to test map in golang? I have a function argmin from the associative array map . The signature of this function is as follows:

 func ArgminMap(m map[int]int) (int, error) 

The problem . map in golang is implemented in such a way that it does not provide any guarantee on how to bypass the elements. If I initialize the map like this:

 m := map[int]int{} for i := 0; i < 10; i++ { m[i] = i } 

then there is no guarantee that with two starts of the program, m will be initialized in the same way. Those. listing:

 for k, v := range m { fmt.Println(k, v) } 

for each new launch may differ from each previous:

  Запуск 1: 0 0 1 1 3 3 5 5 6 6 8 8 9 9 2 2 4 4 7 7 Запуск 2: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0 

The question arises how to compare the answers of the algorithm, if the answer for the argmin function argmin not the only one?

    1 answer 1

    Do what encoding/json packets do and, with Go 1.12 , fmt : take keys, sort, and traverse in sorted order. Mapy does not give any guarantees in order, just as select does not guarantee guarantees in the order in which signals are received, so if you need reproducible results, then it is your job to make them so.

    • Another option is the following. Take into account all possible answers. If the argmin function argmin one of them, then assume that the test has passed - hedgehogues
    • one
      @hedgehogues Depends on the situation. Without context is hard to say. You can even enable / disable sorting via a flag in the code. - Ainar-G