[ACCEPTED]-golang map prints out of order-go

Accepted answer
Score: 17


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)
    for _, i := range si {
        fmt.Printf("%2d: %s\n", i, mm[i])

    return 0, nil

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


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
Score: 6

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

More Related questions