2022-09-16:以下go语言代码输出什么?A:101;B:100;C:1;D:2。
package main
import (
"fmt"
)
type MS struct {
Name string
Cgs int
}
func main() {
hashRun := make(map[string]*MS)
mss := []MS{
MS{Name: "m", Cgs: 100},
MS{Name: "m", Cgs: 1},
}
for _, ms := range mss {
if h, ok := hashRun[ms.Name]; ok {
h.Cgs += ms.Cgs
} else {
hashRun[ms.Name] = &ms
}
}
for _, ms := range hashRun {
fmt.Println(ms.Cgs)
}
}
答案选D。有部分人会选A。这是经典的for range,变量共用问题。