golang map prints out of order

后端 未结 2 387
轻奢々
轻奢々 2020-12-17 20:07

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 s         


        
相关标签:
2条回答
  • 2020-12-17 20:24

    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
    
    0 讨论(0)
  • 2020-12-17 20:33

    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.

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