Search code examples
gobeego

How to range array in golang to not randomize predetermined key?


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.


Solution

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