本帖最后由 Jack2002 于 2021-8-2 19:37 编辑
go的map遍历是是随机的,每次都不一样,需要自行解决排序问题。非常抱歉,中午急着吃饭没认真审题,只是瞟了一眼就认为你的是排序的问题!
[Golang] 纯文本查看 复制代码 package main
import "fmt"
type student struct {
name string
age int
}
func main() {
m := make(map[string]student)
stus := []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
// 非指针类型赋值,可以用for range来遍历并赋值
for _, stu := range stus {
m[stu.name] = stu
}
for k, v := range m {
fmt.Println(k, "=>", v.name, v.age)
}
fmt.Println("-------------------------------")
m2 := make(map[string]*student)
stus = []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
// 指针类型赋值,只能用这种方式来遍历取地址,
for i := 0; i < len(stus); i++ {
m2[stus[i].name] = &stus[i]
}
for k, v := range m2 {
fmt.Println(k, "=>", v.name, v.age)
}
}
|