GolangNote

Golang笔记

GoLang Map key 排序输出的例子

Permalink

由于GoLang Map 结构比较特殊,如果照常规遍历,每次输出的 key 顺序都不同。这是GoLang 团队故意设计的。

GoLang Map key 排序输出

目的是避免人们过于依赖这种通常情况下key的存储顺序和key的添加顺序一致的特性,所以他们把key的遍历顺序随机化了。如果你希望key的输出顺序和添加顺序一致的话,你需要自己去追踪哪个值存储在哪个位置,就像下面的实现:

Go: map key 排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
    "fmt"
    "sort"
)

func main() {
    var m = map[string]int{
        "unix":         0,
        "python":       1,
        "go":           2,
        "javascript":   3,
        "testing":      4,
        "philosophy":   5,
        "startups":     6,
        "productivity": 7,
        "hn":           8,
        "reddit":       9,
        "C++":          10,
    }
    var keys []string
    for k := range m {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    for _, k := range keys {
        fmt.Println("Key:", k, "Value:", m[k])
    }
}

运行输出:

Bash: output
1
2
3
4
5
6
7
8
9
10
11
Key: C++ Value: 10
Key: go Value: 2
Key: hn Value: 8
Key: javascript Value: 3
Key: philosophy Value: 5
Key: productivity Value: 7
Key: python Value: 1
Key: reddit Value: 9
Key: startups Value: 6
Key: testing Value: 4
Key: unix Value: 0

这是 Golang团队大神 Andrew 提供的方法

本文网址: https://golangnote.com/topic/45.html 转摘请注明来源

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Write a Comment to "GoLang Map key 排序输出的例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms