golang map prints out of order

谁说胖子不能爱 提交于 2020-01-10 02:49:13

问题


Why is the map printing out of order, and how do I get it in to order?

package main

import (
    "fmt"
)

type monthsType struct {
    no   int
    text string
}

var months = map[int]string{
    1:"January", 2:"Fabruary", 3:"March", 4:"April", 5:"May", 6:"June",
    7:"July", 8:"August", 9:"September", 10:"October", 11:"Novenber", 12:"December",
}

func main(){
    for no, month := range months {
        fmt.Print(no)
        fmt.Println("-" + month)
    }
}

Prints out:

10-October
7-July
1-January
9-September
4-April
5-May
2-Fabruary
12-December
11-Novenber
6-June
8-August
3-March

回答1:


Code:

func DemoSortMap() (int, error) {
    fmt.Println("use an array to access items by number:")
    am := [2]string{"jan", "feb"}
    for i, n := range am {
        fmt.Printf("%2d: %s\n", i, n)
    }
    fmt.Println("maps are non-sorted:")
    mm := map[int]string{2: "feb", 1: "jan"}
    for i, n := range mm {
        fmt.Printf("%2d: %s\n", i, n)
    }
    fmt.Println("access items via sorted list of keys::")
    si := make([]int, 0, len(mm))
    for i := range mm {
        si = append(si, i)
    }
    sort.Ints(si)
    for _, i := range si {
        fmt.Printf("%2d: %s\n", i, mm[i])
    }

    return 0, nil
}

(most of it stolen from M. Summerfield's book)

output:

use an array to access items by number:
 0: jan
 1: feb
maps are non-sorted:
 2: feb
 1: jan
access items via sorted list of keys::
 1: jan
 2: feb



回答2:


Maps are not sorted so you may use a slice to sort your map. Mark Summerfield's book "Programming in Go" explains this on page 204 and is highly recommended.



来源:https://stackoverflow.com/questions/12108215/golang-map-prints-out-of-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!