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

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境