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

前端 未结 4 906
遥遥无期
遥遥无期 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

    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.

提交回复
热议问题