-2

I have a trouble with my current golang's project.

I have another package in go that result an array with pretedermined key, example :

package updaters

var CustomSql map[string]string

func InitSqlUpdater() {
    CustomSql = map[string]string{
        "ShouldBeFirst": "Text Should Be First",
        "ShouldBeSecond": "Text Should Be Second",
        "ShouldBeThird": "Text Should Be Third",
        "ShouldBeFourth": "Text Should Be Fourth"
   }
}

And send it to main.go, to iterate each index and value, but the results is random (In my situation, I need that in sequence).

Real Case : https://play.golang.org/p/ONXEiAj-Q4v

I google why the golangs iterate in random way, and the example is using sort, but my array keys is predetermined, and sort is only for asc desc alphabet and number.

So, How can I achieve the way that arrays is not being randomize in iterate?

ShouldBeFirst = Text Should Be First
ShouldBeSecond = Text Should Be Second
ShouldBeThird = Text Should Be Third
ShouldBeFourth = Text Should Be Fourth

Anyhelp will appreciate, thanks.

  • golang maps does not guarantee ordered iteration https://stackoverflow.com/questions/18342784/how-to-iterate-through-a-map-in-golang-in-order – Nidhin David Jan 23 '19 at 06:55
  • I think is not duplicate, thats is the key number, but i have keys is predetermined @NidhinDavid , do I have to make integer in keys of array? – Nasihun Amin Suhardiyan Jan 23 '19 at 06:56

1 Answers1

2

The language specification says

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

To iterate over a fixed set of keys in a known order, store those keys in a slice and iterate through the slice elements.

var orderdKeys = []string{
   "ShouldBeFirst", 
   "ShouldBeSecond",
   "ShouldBeThird",
   "ShouldBeFourth",
}

for _, k := range orderdKeys {
    fmt.Println(k+" = "+CustomSql[k])
}

Another option is to use a slice of values:

 type nameSQL struct {
   name string
   sql string
}

CustomSql := []nameSQL{
   {"ShouldBeFirst", "Text Should Be First"},
   {"ShouldBeSecond", "Text Should Be Second"},
   {"ShouldBeThird", "Text Should Be Third"},
   {"ShouldBeFourth", "Text Should Be Fourth"},
}

for _, ns := range CustomSql {
    fmt.Println(ns.name+" = "+ns.sql)
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242