golang地图打印不按顺序

前端之家收集整理的这篇文章主要介绍了golang地图打印不按顺序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么地图打印不正常,我该如何按顺序打印?
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
码:
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",n)
    }
    fmt.Println("access items via sorted list of keys::")
    si := make([]int,len(mm))
    for i := range mm {
        si = append(si,i)
    }
    sort.Ints(si)
    for _,i := range si {
        fmt.Printf("%2d: %s\n",mm[i])
    }

    return 0,nil
}

(其中大部分是从M. Summerfield的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
原文链接:https://www.f2er.com/go/187019.html

猜你在找的Go相关文章