我目前的 golang 項目有問題。我有另一個包,結果是一個帶有預先確定的鍵的數組,例如:package updatersvar CustomSql map[string]stringfunc 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" }}并將其發送到 main.go,以迭代每個索引和值,但結果是隨機的(在我的情況下,我需要按順序)。真實案例: https: //play.golang.org/p/ONXEiAj-Q4v我用谷歌搜索為什么 golang 以隨機方式迭代,示例使用排序,但我的數組鍵是預先確定的,排序僅適用于 asc desc 字母表和數字。那么,我怎樣才能實現數組在迭代中不被隨機化的方式呢?ShouldBeFirst = Text Should Be FirstShouldBeSecond = Text Should Be SecondShouldBeThird = Text Should Be ThirdShouldBeFourth = Text Should Be FourthAnyhelp 將不勝感激,謝謝。
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
語言規范說
未指定地圖上的迭代順序,并且不保證從一次迭代到下一次迭代是相同的。
要以已知順序迭代一組固定的鍵,請將這些鍵存儲在切片中并迭代切片元素。
var orderdKeys = []string{
? ?"ShouldBeFirst",?
? ?"ShouldBeSecond",
? ?"ShouldBeThird",
? ?"ShouldBeFourth",
}
for _, k := range orderdKeys {
? ? fmt.Println(k+" = "+CustomSql[k])
}
另一種選擇是使用一片值:
?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)
}
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消