小编典典

golang地图打印混乱

go

为什么地图打印混乱,如何使它秩序井然?

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)
    }
}

打印输出:

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

阅读 272

收藏
2020-07-02

共1个答案

小编典典

码:

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
}

(其中大部分是从萨默菲尔德先生的书中偷走的)

输出:

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
2020-07-02