doutui6241 2019-01-23 06:50
浏览 111
已采纳

如何在golang中对数组进行排列以不随机化预定键? [重复]

This question already has an answer here:

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.

</div>
  • 写回答

1条回答 默认 最新

  • drno94939847 2019-01-23 06:57
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝