为什么 Go 不能按插入顺序迭代地图? [英] Why can't Go iterate maps in insertion order?

查看:33
本文介绍了为什么 Go 不能按插入顺序迭代地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个导航栏作为地图:

I have a navbar as a map:

var navbar = map[string]navbarTab{
}

其中 navbarTab 具有各种属性、子项等.当我尝试渲染导航栏(使用 for tabKey := range navbar)时,它以随机顺序显示.我知道 range 在运行时会随机排序,但似乎无法获取有序的键列表或按插入顺序迭代.

Where navbarTab has various properties, child items and so on. When I try to render the navbar (with for tabKey := range navbar) it shows up in a random order. I'm aware range randomly sorts when it runs but there appears to be no way to get an ordered list of keys or iterate in the insertion order.

游乐场链接在这里:http://play.golang.org/p/nSL1zhadg5 虽然它似乎没有表现出相同的行为.

The playground link is here: http://play.golang.org/p/nSL1zhadg5 although it seems to not exhibit the same behavior.

如何在不破坏插入顺序的情况下遍历此地图?

How can I iterate over this map without breaking the insertion order?

推荐答案

Go maps 不维护插入顺序;您必须自己实现此行为.

Go maps do not maintain the insertion order; you will have to implement this behavior yourself.

示例:

type NavigationMap struct {
    m map[string]navbarTab
    keys []string
}

func NewNavigationMap() *NavigationMap { ... }

func (n *NavigationMap) Set(k string, v navbarTab) {
    n.m[k] = v
    n.keys = append(n.keys, k)
}

此示例并不完整,并未涵盖所有用例(例如,更新重复键的插入顺序).

This example is not complete and does not cover all use-cases (eg. updating insertion order on duplicate keys).

如果您的用例包括多次重新插入相同的键(如果键 k 已经在映射中,这将不会更新它的插入顺序):

If your use-case includes re-inserting the same key multiple times (this will not update insertion order for key k if it was already in the map):

func (n *NavigationMap) Set(k string, v navbarTab) {
    _, present := n.m[k]
    n.m[k] = v
    if !present {
        n.keys = append(n.keys, k)
    }
}

选择满足您要求的最简单的东西.

Choose the simplest thing that satisfies your requirements.

这篇关于为什么 Go 不能按插入顺序迭代地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆