Why can't iterate maps in input order?

I have navbar as a map:

var navbar = map[string]navbarTab{
}

Where it navbarTabhas various properties, children, etc. When I try to display the navigation bar (s for tabKey := range navbar), it appears in random order. I know that rangerandomly sorts when it starts, but there seems to be no way to get an ordered list of keys or iterate in insertion order.

It seems ridiculous that this is impossible.

A link to the playing field is here: http://play.golang.org/p/nSL1zhadg5 , although it does not seem to display the same behavior.

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

+3
source share
2

Go ; .

:

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)
}

(, ).

( k, ):

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

, .

+11

, -. "" "" .

:

, , - , (key, value), .

, Go . ( ):

, , , . nil.

, "" "" , : "" . ? . , ​​ -, .. , ( ) Go -, , .

Go .

, 1, , , / . , , , , . ( ), , Go 1, , , .

?

( - - ) , , , map . , ( ) . , , .

map, , , map , .

Go , :

. Go 1, runtime , . , , . map[int]string :

import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

P.S:.

... , , .

, " " Go, / Go . , , . , . , , , .

+16

Source: https://habr.com/ru/post/1663119/


All Articles