亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 golang 中調整數組以不隨機化預定鍵?

如何在 golang 中調整數組以不隨機化預定鍵?

Go
互換的青春 2023-06-01 18:05:58
我目前的 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)

}


查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號