求助Go语言基础问题
``` gopackage main
import "fmt"
type student struct {
name string
ageint
}
func main() {
m := make(map*student)
stus := []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
for _, stu := range stus {
m = &stu
}
for k, v := range m {
fmt.Println(k, "=>", v.age)
}
}
```
下面是输出结果
``` go
小王子 => 9000
娜扎 => 9000
大王八 => 9000
```
这里有疑问,为什么输出不是
```go
小王子 => 18
娜扎 => 23
大王八 => 9000
```
求大佬们赐教 本帖最后由 judgecx 于 2021-8-2 11:55 编辑
age定义的值都一样
我盲猜哈我没学过go 本帖最后由 Jack2002 于 2021-8-2 19:37 编辑
go的map遍历是是随机的,每次都不一样,需要自行解决排序问题。非常抱歉,中午急着吃饭没认真审题,只是瞟了一眼就认为你的是排序的问题!
package main
import "fmt"
type student struct {
name string
ageint
}
func main() {
m := make(mapstudent)
stus := []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
// 非指针类型赋值,可以用for range来遍历并赋值
for _, stu := range stus {
m = stu
}
for k, v := range m {
fmt.Println(k, "=>", v.name, v.age)
}
fmt.Println("-------------------------------")
m2 := make(map*student)
stus = []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
// 指针类型赋值,只能用这种方式来遍历取地址,
for i := 0; i < len(stus); i++ {
m2.name] = &stus
}
for k, v := range m2 {
fmt.Println(k, "=>", v.name, v.age)
}
}
judgecx 发表于 2021-8-2 11:53
age定义的值都一样
我盲猜哈我没学过go
age有三个值 Jack2002 发表于 2021-8-2 11:54
go的map遍历是是随机的,每次都不一样,需要自行解决排序问题。
可是把map的值value的结构体指针*student换成结构体student的话,再遍历age值就不一样了 package main
import "fmt"
type student struct {
name string
ageint
}
func main() {
m := make(map*student)
stus := []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
for i := 0; i < len(stu);i++{
m.name] = &stu
}
for k, v := range m {
fmt.Println(k, "=>", v.age)
}
} 调试一下看看,这种问题就别盯着代码分析了 package main
import "fmt"
type student struct {
name string
ageint
}
func main() {
m := make(map*student)
stus := []student{
{name: "小王子", age: 18},
{name: "娜扎", age: 23},
{name: "大王八", age: 9000},
}
for _, stu := range stus {
m = &stu
}
for k, v := range m {
fmt.Println(k, "=>", v.age)
}
for _, v := range m {
fmt.Println(v.name, "=>", v.age)
}
}
输出是:
小王子 => 9000
娜扎 => 9000
大王八 => 9000
大王八 => 9000
大王八 => 9000
大王八 => 9000
懂了吧 侃遍天下无二人 发表于 2021-8-2 12:21
调试一下看看,这种问题就别盯着代码分析了
谢谢大佬 ch_jm0723 发表于 2021-8-2 12:30
package main
import "fmt"
可能我太蠢了,还是不懂