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

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

问题描述

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

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.

这是不可能的,这是不可能的。

It seems ridiculous this isn't possible.

操场链接在这里: 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 does not maintain the插入顺序;您将不得不自行实施此行为。

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(m.keys, k)
}

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

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