首页 >后端开发 >Golang >如何按特定顺序迭代 Go Map?

如何按特定顺序迭代 Go Map?

DDD
DDD原创
2024-12-07 16:58:15347浏览

How to Iterate Through Go Maps in a Specific Order?

为什么地图打印顺序不正确

在 Go 中,地图是键值对的无序集合。这意味着无法保证映射中元素的顺序。当您迭代地图时,元素会以任意顺序返回,如果您需要特定的顺序,这可能会造成混乱或出现问题。

按顺序获取地图

要按顺序获取地图,可以使用 sort 包。这是一个示例:

package main

import (
    "fmt"
    "sort"
)

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(){
    // Create a slice of the map keys
    keys := make([]int, len(months))
    i := 0
    for key := range months {
        keys[i] = key
        i++
    }

    // Sort the slice of keys
    sort.Ints(keys)

    // Iterate over the keys and print the corresponding values
    for _, key := range keys {
        fmt.Println(key, "-", months[key])
    }
}

此代码将以键的升序输出地图元素:

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

以上是如何按特定顺序迭代 Go Map?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn