如何在 golang 中调整数组以不随机化预定键?
How to range array in golang to not randomize predetermined key?
我目前的golang项目有问题
我在 go 中有另一个包,它生成一个带有预定键的数组,例如:
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"
}
}
并将其发送到 main.go,以迭代每个索引和值,但结果是随机的(在我的情况下,我需要按顺序)。
真实案例:https://play.golang.org/p/ONXEiAj-Q4v
我google为什么golang是随机迭代的,这个例子是用排序,但是我的数组键是预先确定的,排序只针对asc desc字母和数字。
那么,我怎样才能实现数组在迭代中不被随机化的方式呢?
ShouldBeFirst = Text Should Be First
ShouldBeSecond = Text Should Be Second
ShouldBeThird = Text Should Be Third
ShouldBeFourth = Text Should Be Fourth
任何帮助将不胜感激,谢谢。
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.
要以已知顺序迭代一组固定键,请将这些键存储在切片中并迭代切片元素。
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)
}
我目前的golang项目有问题
我在 go 中有另一个包,它生成一个带有预定键的数组,例如:
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"
}
}
并将其发送到 main.go,以迭代每个索引和值,但结果是随机的(在我的情况下,我需要按顺序)。
真实案例:https://play.golang.org/p/ONXEiAj-Q4v
我google为什么golang是随机迭代的,这个例子是用排序,但是我的数组键是预先确定的,排序只针对asc desc字母和数字。
那么,我怎样才能实现数组在迭代中不被随机化的方式呢?
ShouldBeFirst = Text Should Be First
ShouldBeSecond = Text Should Be Second
ShouldBeThird = Text Should Be Third
ShouldBeFourth = Text Should Be Fourth
任何帮助将不胜感激,谢谢。
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.
要以已知顺序迭代一组固定键,请将这些键存储在切片中并迭代切片元素。
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)
}