Why does Go's map iteration order vary when printing?

前端 未结 4 873
遥遥无期
遥遥无期 2020-12-18 12:48
package main

import \"fmt\"

func main(){
    sample := map[string]string{
    \"key1\":\"value1\",
    \"key2\":\"value2\",
    \"key3\":\"value3\",
    }
    for          


        
相关标签:
4条回答
  • 2020-12-18 13:26

    Python does not guarantee the order of iteration, but it does guarantee that the order will remain stable so long as you do not modify the dictionary between calls:

    If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are
    called with no intervening modifications to the dictionary, the lists will 
    directly correspond.
    

    Go does not guarantee either. It looks from your example as though the order in Go may be stable and only the starting point varies, but as nothing is guaranteed don't depend on it.

    0 讨论(0)
  • 2020-12-18 13:26

    As I understand that you should not depend on the order of the iterator for the map, since it has no logical ordering.

    That aside, I believe that Go's implementation for map iteration is intentionally random (http://nathanleclaire.com/blog/2014/04/27/a-surprising-feature-of-golang-that-colored-me-impressed/ and http://www.confreaks.com/videos/3419-gophercon2014-opening-day-keynote) that is to discourage people from relying on it in their code.

    I hope that helps.

    0 讨论(0)
  • 2020-12-18 13:32

    You cannot rely on the order in which you will get the keys. The language spec says "A map is an unordered group of elements", and later "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next."

    0 讨论(0)
  • 2020-12-18 13:37

    Yes, it varies and even intentionally (iteration of a non modified map has been stable before). The intent is to catch as early as possible the situation when someone wrongly assumes a stable iteration guarantee. Additionally, with the added freedom for map implementation there comes more possible future optimizations of that part of the run time library.

    0 讨论(0)
提交回复
热议问题